/*!
 * TSRPC Browser v3.4.16
 * -----------------------------------------
 * Copyright (c) King Wang.
 * MIT License
 * https://github.com/k8w/tsrpc-browser
 */
(function (global, factory) {
    typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
    typeof define === 'function' && define.amd ? define(['exports'], factory) :
    (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.tsrpc = {}));
})(this, (function (exports) { 'use strict';

    ///<reference path="index.d.ts"/>
    var _a$1;
    var extendFuncs = {
        remove: function (filter) {
            if (typeof (filter) == 'function') {
                for (var i = this.length - 1; i > -1; --i) {
                    filter(this[i], i, this) && this.splice(i, 1);
                }
            }
            else {
                for (var i = this.length - 1; i > -1; --i) {
                    this[i] === filter && this.splice(i, 1);
                }
            }
            return this;
        },
        removeOne: function (filter) {
            if (typeof (filter) == 'function') {
                for (var i = 0; i < this.length; ++i) {
                    if (filter(this[i], i, this)) {
                        this.splice(i, 1);
                        return this;
                    }
                }
            }
            else {
                for (var i = 0; i < this.length; ++i) {
                    if (this[i] === filter) {
                        this.splice(i, 1);
                        return this;
                    }
                }
            }
            return this;
        },
        first: function () {
            return this.length ? this[0] : null;
        },
        last: function () {
            return this.length ? this[this.length - 1] : null;
        },
        max: function (mapper) {
            if (!this.length) {
                return null;
            }
            if (typeof (mapper) == 'function') {
                var max = mapper(this[0], 0, this);
                for (var i = 1; i < this.length; ++i) {
                    var temp = mapper(this[i], i, this);
                    max = temp > max ? temp : max;
                }
                return max;
            }
            else {
                return this.reduce(function (prev, cur) { return prev > cur ? prev : cur; });
            }
        },
        min: function (mapper) {
            if (!this.length) {
                return null;
            }
            function _min(a, b) {
                return a < b ? a : b;
            }
            if (typeof (mapper) == 'function') {
                var min = mapper(this[0], 0, this);
                for (var i = 1; i < this.length; ++i) {
                    var temp = mapper(this[i], i, this);
                    min = temp < min ? temp : min;
                }
                return min;
            }
            else {
                return this.reduce(function (prev, cur) { return _min(prev, cur); });
            }
        },
        distinct: function () {
            return this.filter(function (v, i, arr) { return arr.indexOf(v) === i; });
        },
        filterIndex: function (filter) {
            var output = [];
            for (var i = 0; i < this.length; ++i) {
                if (filter(this[i], i, this)) {
                    output.push(i);
                }
            }
            return output;
        },
        count: function (filter) {
            var result = 0;
            for (var i = 0; i < this.length; ++i) {
                if (filter(this[i], i, this)) {
                    ++result;
                }
            }
            return result;
        },
        sum: function (mapper) {
            var result = 0;
            for (var i = 0; i < this.length; ++i) {
                result += mapper ? mapper(this[i], i, this) : this[i];
            }
            return result;
        },
        average: function (mapper) {
            return this.sum(mapper) / this.length;
        },
        orderBy: function () {
            var mappers = [];
            for (var _i = 0; _i < arguments.length; _i++) {
                mappers[_i] = arguments[_i];
            }
            return this.slice().sort(function (a, b) {
                for (var i = 0; i < mappers.length; ++i) {
                    var va = mappers[i](a);
                    var vb = mappers[i](b);
                    if (va > vb) {
                        return 1;
                    }
                    else if (va < vb) {
                        return -1;
                    }
                }
                return 0;
            });
        },
        orderByDesc: function () {
            var mappers = [];
            for (var _i = 0; _i < arguments.length; _i++) {
                mappers[_i] = arguments[_i];
            }
            return this.slice().sort(function (a, b) {
                for (var i = 0; i < mappers.length; ++i) {
                    var va = mappers[i](a);
                    var vb = mappers[i](b);
                    if (va > vb) {
                        return -1;
                    }
                    else if (va < vb) {
                        return 1;
                    }
                }
                return 0;
            });
        },
        binarySearch: function (value, keyMapper) {
            var low = 0, high = this.length - 1;
            while (low <= high) {
                var mid = ((high + low) / 2) | 0;
                var midValue = keyMapper ? keyMapper(this[mid]) : this[mid];
                if (value === midValue) {
                    return mid;
                }
                else if (value > midValue) {
                    low = mid + 1;
                }
                else if (value < midValue) {
                    high = mid - 1;
                }
            }
            return -1;
        },
        binaryInsert: function (item, keyMapper, unique) {
            if (typeof (keyMapper) == 'boolean') {
                unique = keyMapper;
                keyMapper = undefined;
            }
            var low = 0, high = this.length - 1;
            var mid = NaN;
            var itemValue = keyMapper ? keyMapper(item) : item;
            while (low <= high) {
                mid = ((high + low) / 2) | 0;
                var midValue = keyMapper ? keyMapper(this[mid]) : this[mid];
                if (itemValue === midValue) {
                    if (unique) {
                        return mid;
                    }
                    else {
                        break;
                    }
                }
                else if (itemValue > midValue) {
                    low = mid + 1;
                }
                else if (itemValue < midValue) {
                    high = mid - 1;
                }
            }
            var index = low > mid ? mid + 1 : mid;
            this.splice(index, 0, item);
            return index;
        },
        binaryDistinct: function (keyMapper) {
            return this.filter(function (v, i, arr) { return arr.binarySearch(v, keyMapper) === i; });
        },
        findLast: function (predicate) {
            for (var i = this.length - 1; i > -1; --i) {
                if (predicate(this[i], i, this)) {
                    return this[i];
                }
            }
            return undefined;
        },
        findLastIndex: function (predicate) {
            for (var i = this.length - 1; i > -1; --i) {
                if (predicate(this[i], i, this)) {
                    return i;
                }
            }
            return -1;
        },
        groupBy: function (grouper) {
            var group = this.reduce(function (prev, next) {
                var groupKey = grouper(next);
                if (!prev[groupKey]) {
                    prev[groupKey] = [];
                }
                prev[groupKey].push(next);
                return prev;
            }, {});
            return Object.keys(group).map(function (key) {
                var arr = group[key];
                arr.key = key;
                return arr;
            });
        },
        __k8w_extended: {
            value: true
        }
    };
    if (!Array.prototype.__k8w_extended) {
        for (var key in extendFuncs) {
            Object.defineProperties(Array.prototype, (_a$1 = {},
                _a$1[key] = {
                    value: extendFuncs[key],
                    writable: true
                },
                _a$1));
        }
    }

    ///<reference path="index.d.ts"/>
    function prependZero(matched, num) {
        return matched.length > 1 && num < 10 ? "0" + num : "" + num;
    }
    Date.prototype.format = function (pattern) {
        var _this = this;
        if (pattern === void 0) { pattern = 'YYYY-MM-DD hh:mm:ss'; }
        return pattern.replace(/y{2,}|Y{2,}/, function (v) { return (_this.getFullYear() + "").substr(4 - v.length); })
            .replace(/M{1,2}/, function (v) { return prependZero(v, _this.getMonth() + 1); })
            .replace(/D{1,2}|d{1,2}/, function (v) { return prependZero(v, _this.getDate()); })
            .replace(/Q|q/, function (v) { return prependZero(v, Math.ceil((_this.getMonth() + 1) / 3)); })
            .replace(/h{1,2}|H{1,2}/, function (v) { return prependZero(v, _this.getHours()); })
            .replace(/m{1,2}/, function (v) { return prependZero(v, _this.getMinutes()); })
            .replace(/s{1,2}/, function (v) { return prependZero(v, _this.getSeconds()); })
            .replace(/SSS|S/, function (v) {
            var ms = '' + _this.getMilliseconds();
            return v.length === 1 ? ms : "" + (ms.length === 1 ? '00' : ms.length === 2 ? '0' : '') + ms;
        });
    };
    Date.today = function () {
        var now = new Date();
        return new Date(now.getFullYear(), now.getMonth(), now.getDate()).getTime();
    };

    ///<reference path="index.d.ts"/>
    /**
     * 将sources合并到target，该合并全部是深拷贝
     * @param target
     * @param sources
     * @returns {Object}
     */
    Object.merge = function (target) {
        var sources = [];
        for (var _i = 1; _i < arguments.length; _i++) {
            sources[_i - 1] = arguments[_i];
        }
        for (var i = 0; i < sources.length; ++i) {
            var source = sources[i];
            if (typeof source != 'object' || source == null) {
                continue;
            }
            for (var skey in source) {
                //只处理自身的key 这里可能来自于外部prototype的扩展
                if (!source.hasOwnProperty(skey)) {
                    continue;
                }
                if (source[skey] instanceof Date) {
                    //Date类型 要克隆一份 保证深拷贝
                    target[skey] = new Date(source[skey]);
                    continue;
                }
                else if (typeof (target[skey]) == 'object' && target[skey] != null && typeof (source[skey]) == 'object' && source[skey] != null) {
                    // 两个都是Object 递归merge之
                    Object.merge(target[skey], source[skey]);
                }
                else {
                    if (Array.isArray(source[skey])) {
                        // 数组merge后还是数组
                        target[skey] = Object.merge([], source[skey]);
                    }
                    else if (typeof (source[skey]) == 'object' && source[skey] !== null) {
                        // Object要克隆一份以确保深拷贝
                        target[skey] = Object.merge({}, source[skey]);
                    }
                    else {
                        // 基本类型 直接赋值即可
                        target[skey] = source[skey];
                    }
                }
            }
        }
        return target;
    };
    if (!Object.values) {
        Object.values = function (obj) {
            var output = [];
            for (var k in obj) {
                obj.hasOwnProperty(k) && output.push(obj[k]);
            }
            return output;
        };
    }
    if (!Object.entries) {
        Object.entries = function (obj) {
            var output = [];
            for (var key in obj) {
                if (!obj.hasOwnProperty(key)) {
                    continue;
                }
                output.push([key, obj[key]]);
            }
            return output;
        };
    }
    Object.forEach = function (obj, handler) {
        for (var key in obj) {
            if (!obj.hasOwnProperty(key)) {
                return;
            }
            handler(obj[key], key, obj);
        }
    };

    //应对IE9以下没有console
    if (typeof window != 'undefined' && !window.console) {
        window.console = {};
        console.log = console.debug = console.info = console.warn = console.error = console.time = console.timeEnd = function () { };
    }
    //应对某些浏览器没有console.debug的情况
    if (!console.debug) {
        console.debug = console.log;
    }

    var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};

    var check = function (it) {
      return it && it.Math === Math && it;
    };

    // https://github.com/zloirock/core-js/issues/86#issuecomment-115759028
    var globalThis_1 =
      // eslint-disable-next-line es/no-global-this -- safe
      check(typeof globalThis == 'object' && globalThis) ||
      check(typeof window == 'object' && window) ||
      // eslint-disable-next-line no-restricted-globals -- safe
      check(typeof self == 'object' && self) ||
      check(typeof commonjsGlobal == 'object' && commonjsGlobal) ||
      check(typeof commonjsGlobal == 'object' && commonjsGlobal) ||
      // eslint-disable-next-line no-new-func -- fallback
      (function () { return this; })() || Function('return this')();

    var sharedStore = {exports: {}};

    var isPure = false;

    var globalThis$B = globalThis_1;

    // eslint-disable-next-line es/no-object-defineproperty -- safe
    var defineProperty$8 = Object.defineProperty;

    var defineGlobalProperty$3 = function (key, value) {
      try {
        defineProperty$8(globalThis$B, key, { value: value, configurable: true, writable: true });
      } catch (error) {
        globalThis$B[key] = value;
      } return value;
    };

    var globalThis$A = globalThis_1;
    var defineGlobalProperty$2 = defineGlobalProperty$3;

    var SHARED = '__core-js_shared__';
    var store$3 = sharedStore.exports = globalThis$A[SHARED] || defineGlobalProperty$2(SHARED, {});

    (store$3.versions || (store$3.versions = [])).push({
      version: '3.38.1',
      mode: 'global',
      copyright: '© 2014-2024 Denis Pushkarev (zloirock.ru)',
      license: 'https://github.com/zloirock/core-js/blob/v3.38.1/LICENSE',
      source: 'https://github.com/zloirock/core-js'
    });

    var store$2 = sharedStore.exports;

    var shared$4 = function (key, value) {
      return store$2[key] || (store$2[key] = value || {});
    };

    var fails$C = function (exec) {
      try {
        return !!exec();
      } catch (error) {
        return true;
      }
    };

    var fails$B = fails$C;

    var functionBindNative = !fails$B(function () {
      // eslint-disable-next-line es/no-function-prototype-bind -- safe
      var test = (function () { /* empty */ }).bind();
      // eslint-disable-next-line no-prototype-builtins -- safe
      return typeof test != 'function' || test.hasOwnProperty('prototype');
    });

    var NATIVE_BIND$3 = functionBindNative;

    var FunctionPrototype$3 = Function.prototype;
    var call$q = FunctionPrototype$3.call;
    var uncurryThisWithBind = NATIVE_BIND$3 && FunctionPrototype$3.bind.bind(call$q, call$q);

    var functionUncurryThis = NATIVE_BIND$3 ? uncurryThisWithBind : function (fn) {
      return function () {
        return call$q.apply(fn, arguments);
      };
    };

    // we can't use just `it == null` since of `document.all` special case
    // https://tc39.es/ecma262/#sec-IsHTMLDDA-internal-slot-aec
    var isNullOrUndefined$5 = function (it) {
      return it === null || it === undefined;
    };

    var isNullOrUndefined$4 = isNullOrUndefined$5;

    var $TypeError$k = TypeError;

    // `RequireObjectCoercible` abstract operation
    // https://tc39.es/ecma262/#sec-requireobjectcoercible
    var requireObjectCoercible$9 = function (it) {
      if (isNullOrUndefined$4(it)) throw new $TypeError$k("Can't call method on " + it);
      return it;
    };

    var requireObjectCoercible$8 = requireObjectCoercible$9;

    var $Object$4 = Object;

    // `ToObject` abstract operation
    // https://tc39.es/ecma262/#sec-toobject
    var toObject$c = function (argument) {
      return $Object$4(requireObjectCoercible$8(argument));
    };

    var uncurryThis$D = functionUncurryThis;
    var toObject$b = toObject$c;

    var hasOwnProperty = uncurryThis$D({}.hasOwnProperty);

    // `HasOwnProperty` abstract operation
    // https://tc39.es/ecma262/#sec-hasownproperty
    // eslint-disable-next-line es/no-object-hasown -- safe
    var hasOwnProperty_1 = Object.hasOwn || function hasOwn(it, key) {
      return hasOwnProperty(toObject$b(it), key);
    };

    var uncurryThis$C = functionUncurryThis;

    var id = 0;
    var postfix = Math.random();
    var toString$f = uncurryThis$C(1.0.toString);

    var uid$3 = function (key) {
      return 'Symbol(' + (key === undefined ? '' : key) + ')_' + toString$f(++id + postfix, 36);
    };

    var globalThis$z = globalThis_1;

    var navigator$1 = globalThis$z.navigator;
    var userAgent$7 = navigator$1 && navigator$1.userAgent;

    var environmentUserAgent = userAgent$7 ? String(userAgent$7) : '';

    var globalThis$y = globalThis_1;
    var userAgent$6 = environmentUserAgent;

    var process$3 = globalThis$y.process;
    var Deno$1 = globalThis$y.Deno;
    var versions = process$3 && process$3.versions || Deno$1 && Deno$1.version;
    var v8 = versions && versions.v8;
    var match, version;

    if (v8) {
      match = v8.split('.');
      // in old Chrome, versions of V8 isn't V8 = Chrome / 10
      // but their correct versions are not interesting for us
      version = match[0] > 0 && match[0] < 4 ? 1 : +(match[0] + match[1]);
    }

    // BrowserFS NodeJS `process` polyfill incorrectly set `.v8` to `0.0`
    // so check `userAgent` even if `.v8` exists, but 0
    if (!version && userAgent$6) {
      match = userAgent$6.match(/Edge\/(\d+)/);
      if (!match || match[1] >= 74) {
        match = userAgent$6.match(/Chrome\/(\d+)/);
        if (match) version = +match[1];
      }
    }

    var environmentV8Version = version;

    /* eslint-disable es/no-symbol -- required for testing */
    var V8_VERSION$2 = environmentV8Version;
    var fails$A = fails$C;
    var globalThis$x = globalThis_1;

    var $String$6 = globalThis$x.String;

    // eslint-disable-next-line es/no-object-getownpropertysymbols -- required for testing
    var symbolConstructorDetection = !!Object.getOwnPropertySymbols && !fails$A(function () {
      var symbol = Symbol('symbol detection');
      // Chrome 38 Symbol has incorrect toString conversion
      // `get-own-property-symbols` polyfill symbols converted to object are not Symbol instances
      // nb: Do not call `String` directly to avoid this being optimized out to `symbol+''` which will,
      // of course, fail.
      return !$String$6(symbol) || !(Object(symbol) instanceof Symbol) ||
        // Chrome 38-40 symbols are not inherited from DOM collections prototypes to instances
        !Symbol.sham && V8_VERSION$2 && V8_VERSION$2 < 41;
    });

    /* eslint-disable es/no-symbol -- required for testing */
    var NATIVE_SYMBOL$2 = symbolConstructorDetection;

    var useSymbolAsUid = NATIVE_SYMBOL$2
      && !Symbol.sham
      && typeof Symbol.iterator == 'symbol';

    var globalThis$w = globalThis_1;
    var shared$3 = shared$4;
    var hasOwn$e = hasOwnProperty_1;
    var uid$2 = uid$3;
    var NATIVE_SYMBOL$1 = symbolConstructorDetection;
    var USE_SYMBOL_AS_UID$1 = useSymbolAsUid;

    var Symbol$2 = globalThis$w.Symbol;
    var WellKnownSymbolsStore = shared$3('wks');
    var createWellKnownSymbol = USE_SYMBOL_AS_UID$1 ? Symbol$2['for'] || Symbol$2 : Symbol$2 && Symbol$2.withoutSetter || uid$2;

    var wellKnownSymbol$n = function (name) {
      if (!hasOwn$e(WellKnownSymbolsStore, name)) {
        WellKnownSymbolsStore[name] = NATIVE_SYMBOL$1 && hasOwn$e(Symbol$2, name)
          ? Symbol$2[name]
          : createWellKnownSymbol('Symbol.' + name);
      } return WellKnownSymbolsStore[name];
    };

    var wellKnownSymbol$m = wellKnownSymbol$n;

    var TO_STRING_TAG$3 = wellKnownSymbol$m('toStringTag');
    var test = {};

    test[TO_STRING_TAG$3] = 'z';

    var toStringTagSupport = String(test) === '[object z]';

    // https://tc39.es/ecma262/#sec-IsHTMLDDA-internal-slot
    var documentAll = typeof document == 'object' && document.all;

    // `IsCallable` abstract operation
    // https://tc39.es/ecma262/#sec-iscallable
    // eslint-disable-next-line unicorn/no-typeof-undefined -- required for testing
    var isCallable$p = typeof documentAll == 'undefined' && documentAll !== undefined ? function (argument) {
      return typeof argument == 'function' || argument === documentAll;
    } : function (argument) {
      return typeof argument == 'function';
    };

    var objectDefineProperty = {};

    var fails$z = fails$C;

    // Detect IE8's incomplete defineProperty implementation
    var descriptors = !fails$z(function () {
      // eslint-disable-next-line es/no-object-defineproperty -- required for testing
      return Object.defineProperty({}, 1, { get: function () { return 7; } })[1] !== 7;
    });

    var isCallable$o = isCallable$p;

    var isObject$h = function (it) {
      return typeof it == 'object' ? it !== null : isCallable$o(it);
    };

    var globalThis$v = globalThis_1;
    var isObject$g = isObject$h;

    var document$3 = globalThis$v.document;
    // typeof document.createElement is 'object' in old IE
    var EXISTS$1 = isObject$g(document$3) && isObject$g(document$3.createElement);

    var documentCreateElement$2 = function (it) {
      return EXISTS$1 ? document$3.createElement(it) : {};
    };

    var DESCRIPTORS$l = descriptors;
    var fails$y = fails$C;
    var createElement$1 = documentCreateElement$2;

    // Thanks to IE8 for its funny defineProperty
    var ie8DomDefine = !DESCRIPTORS$l && !fails$y(function () {
      // eslint-disable-next-line es/no-object-defineproperty -- required for testing
      return Object.defineProperty(createElement$1('div'), 'a', {
        get: function () { return 7; }
      }).a !== 7;
    });

    var DESCRIPTORS$k = descriptors;
    var fails$x = fails$C;

    // V8 ~ Chrome 36-
    // https://bugs.chromium.org/p/v8/issues/detail?id=3334
    var v8PrototypeDefineBug = DESCRIPTORS$k && fails$x(function () {
      // eslint-disable-next-line es/no-object-defineproperty -- required for testing
      return Object.defineProperty(function () { /* empty */ }, 'prototype', {
        value: 42,
        writable: false
      }).prototype !== 42;
    });

    var isObject$f = isObject$h;

    var $String$5 = String;
    var $TypeError$j = TypeError;

    // `Assert: Type(argument) is Object`
    var anObject$g = function (argument) {
      if (isObject$f(argument)) return argument;
      throw new $TypeError$j($String$5(argument) + ' is not an object');
    };

    var NATIVE_BIND$2 = functionBindNative;

    var call$p = Function.prototype.call;

    var functionCall = NATIVE_BIND$2 ? call$p.bind(call$p) : function () {
      return call$p.apply(call$p, arguments);
    };

    var globalThis$u = globalThis_1;
    var isCallable$n = isCallable$p;

    var aFunction = function (argument) {
      return isCallable$n(argument) ? argument : undefined;
    };

    var getBuiltIn$8 = function (namespace, method) {
      return arguments.length < 2 ? aFunction(globalThis$u[namespace]) : globalThis$u[namespace] && globalThis$u[namespace][method];
    };

    var uncurryThis$B = functionUncurryThis;

    var objectIsPrototypeOf = uncurryThis$B({}.isPrototypeOf);

    var getBuiltIn$7 = getBuiltIn$8;
    var isCallable$m = isCallable$p;
    var isPrototypeOf$7 = objectIsPrototypeOf;
    var USE_SYMBOL_AS_UID = useSymbolAsUid;

    var $Object$3 = Object;

    var isSymbol$5 = USE_SYMBOL_AS_UID ? function (it) {
      return typeof it == 'symbol';
    } : function (it) {
      var $Symbol = getBuiltIn$7('Symbol');
      return isCallable$m($Symbol) && isPrototypeOf$7($Symbol.prototype, $Object$3(it));
    };

    var $String$4 = String;

    var tryToString$6 = function (argument) {
      try {
        return $String$4(argument);
      } catch (error) {
        return 'Object';
      }
    };

    var isCallable$l = isCallable$p;
    var tryToString$5 = tryToString$6;

    var $TypeError$i = TypeError;

    // `Assert: IsCallable(argument) is true`
    var aCallable$a = function (argument) {
      if (isCallable$l(argument)) return argument;
      throw new $TypeError$i(tryToString$5(argument) + ' is not a function');
    };

    var aCallable$9 = aCallable$a;
    var isNullOrUndefined$3 = isNullOrUndefined$5;

    // `GetMethod` abstract operation
    // https://tc39.es/ecma262/#sec-getmethod
    var getMethod$4 = function (V, P) {
      var func = V[P];
      return isNullOrUndefined$3(func) ? undefined : aCallable$9(func);
    };

    var call$o = functionCall;
    var isCallable$k = isCallable$p;
    var isObject$e = isObject$h;

    var $TypeError$h = TypeError;

    // `OrdinaryToPrimitive` abstract operation
    // https://tc39.es/ecma262/#sec-ordinarytoprimitive
    var ordinaryToPrimitive$1 = function (input, pref) {
      var fn, val;
      if (pref === 'string' && isCallable$k(fn = input.toString) && !isObject$e(val = call$o(fn, input))) return val;
      if (isCallable$k(fn = input.valueOf) && !isObject$e(val = call$o(fn, input))) return val;
      if (pref !== 'string' && isCallable$k(fn = input.toString) && !isObject$e(val = call$o(fn, input))) return val;
      throw new $TypeError$h("Can't convert object to primitive value");
    };

    var call$n = functionCall;
    var isObject$d = isObject$h;
    var isSymbol$4 = isSymbol$5;
    var getMethod$3 = getMethod$4;
    var ordinaryToPrimitive = ordinaryToPrimitive$1;
    var wellKnownSymbol$l = wellKnownSymbol$n;

    var $TypeError$g = TypeError;
    var TO_PRIMITIVE = wellKnownSymbol$l('toPrimitive');

    // `ToPrimitive` abstract operation
    // https://tc39.es/ecma262/#sec-toprimitive
    var toPrimitive$3 = function (input, pref) {
      if (!isObject$d(input) || isSymbol$4(input)) return input;
      var exoticToPrim = getMethod$3(input, TO_PRIMITIVE);
      var result;
      if (exoticToPrim) {
        if (pref === undefined) pref = 'default';
        result = call$n(exoticToPrim, input, pref);
        if (!isObject$d(result) || isSymbol$4(result)) return result;
        throw new $TypeError$g("Can't convert object to primitive value");
      }
      if (pref === undefined) pref = 'number';
      return ordinaryToPrimitive(input, pref);
    };

    var toPrimitive$2 = toPrimitive$3;
    var isSymbol$3 = isSymbol$5;

    // `ToPropertyKey` abstract operation
    // https://tc39.es/ecma262/#sec-topropertykey
    var toPropertyKey$3 = function (argument) {
      var key = toPrimitive$2(argument, 'string');
      return isSymbol$3(key) ? key : key + '';
    };

    var DESCRIPTORS$j = descriptors;
    var IE8_DOM_DEFINE$1 = ie8DomDefine;
    var V8_PROTOTYPE_DEFINE_BUG$1 = v8PrototypeDefineBug;
    var anObject$f = anObject$g;
    var toPropertyKey$2 = toPropertyKey$3;

    var $TypeError$f = TypeError;
    // eslint-disable-next-line es/no-object-defineproperty -- safe
    var $defineProperty = Object.defineProperty;
    // eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe
    var $getOwnPropertyDescriptor$1 = Object.getOwnPropertyDescriptor;
    var ENUMERABLE = 'enumerable';
    var CONFIGURABLE$1 = 'configurable';
    var WRITABLE = 'writable';

    // `Object.defineProperty` method
    // https://tc39.es/ecma262/#sec-object.defineproperty
    objectDefineProperty.f = DESCRIPTORS$j ? V8_PROTOTYPE_DEFINE_BUG$1 ? function defineProperty(O, P, Attributes) {
      anObject$f(O);
      P = toPropertyKey$2(P);
      anObject$f(Attributes);
      if (typeof O === 'function' && P === 'prototype' && 'value' in Attributes && WRITABLE in Attributes && !Attributes[WRITABLE]) {
        var current = $getOwnPropertyDescriptor$1(O, P);
        if (current && current[WRITABLE]) {
          O[P] = Attributes.value;
          Attributes = {
            configurable: CONFIGURABLE$1 in Attributes ? Attributes[CONFIGURABLE$1] : current[CONFIGURABLE$1],
            enumerable: ENUMERABLE in Attributes ? Attributes[ENUMERABLE] : current[ENUMERABLE],
            writable: false
          };
        }
      } return $defineProperty(O, P, Attributes);
    } : $defineProperty : function defineProperty(O, P, Attributes) {
      anObject$f(O);
      P = toPropertyKey$2(P);
      anObject$f(Attributes);
      if (IE8_DOM_DEFINE$1) try {
        return $defineProperty(O, P, Attributes);
      } catch (error) { /* empty */ }
      if ('get' in Attributes || 'set' in Attributes) throw new $TypeError$f('Accessors not supported');
      if ('value' in Attributes) O[P] = Attributes.value;
      return O;
    };

    var makeBuiltIn$3 = {exports: {}};

    var DESCRIPTORS$i = descriptors;
    var hasOwn$d = hasOwnProperty_1;

    var FunctionPrototype$2 = Function.prototype;
    // eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe
    var getDescriptor = DESCRIPTORS$i && Object.getOwnPropertyDescriptor;

    var EXISTS = hasOwn$d(FunctionPrototype$2, 'name');
    // additional protection from minified / mangled / dropped function names
    var PROPER = EXISTS && (function something() { /* empty */ }).name === 'something';
    var CONFIGURABLE = EXISTS && (!DESCRIPTORS$i || (DESCRIPTORS$i && getDescriptor(FunctionPrototype$2, 'name').configurable));

    var functionName = {
      EXISTS: EXISTS,
      PROPER: PROPER,
      CONFIGURABLE: CONFIGURABLE
    };

    var uncurryThis$A = functionUncurryThis;
    var isCallable$j = isCallable$p;
    var store$1 = sharedStore.exports;

    var functionToString$1 = uncurryThis$A(Function.toString);

    // this helper broken in `core-js@3.4.1-3.4.4`, so we can't use `shared` helper
    if (!isCallable$j(store$1.inspectSource)) {
      store$1.inspectSource = function (it) {
        return functionToString$1(it);
      };
    }

    var inspectSource$3 = store$1.inspectSource;

    var globalThis$t = globalThis_1;
    var isCallable$i = isCallable$p;

    var WeakMap$2 = globalThis$t.WeakMap;

    var weakMapBasicDetection = isCallable$i(WeakMap$2) && /native code/.test(String(WeakMap$2));

    var createPropertyDescriptor$5 = function (bitmap, value) {
      return {
        enumerable: !(bitmap & 1),
        configurable: !(bitmap & 2),
        writable: !(bitmap & 4),
        value: value
      };
    };

    var DESCRIPTORS$h = descriptors;
    var definePropertyModule$5 = objectDefineProperty;
    var createPropertyDescriptor$4 = createPropertyDescriptor$5;

    var createNonEnumerableProperty$a = DESCRIPTORS$h ? function (object, key, value) {
      return definePropertyModule$5.f(object, key, createPropertyDescriptor$4(1, value));
    } : function (object, key, value) {
      object[key] = value;
      return object;
    };

    var shared$2 = shared$4;
    var uid$1 = uid$3;

    var keys$1 = shared$2('keys');

    var sharedKey$3 = function (key) {
      return keys$1[key] || (keys$1[key] = uid$1(key));
    };

    var hiddenKeys$4 = {};

    var NATIVE_WEAK_MAP = weakMapBasicDetection;
    var globalThis$s = globalThis_1;
    var isObject$c = isObject$h;
    var createNonEnumerableProperty$9 = createNonEnumerableProperty$a;
    var hasOwn$c = hasOwnProperty_1;
    var shared$1 = sharedStore.exports;
    var sharedKey$2 = sharedKey$3;
    var hiddenKeys$3 = hiddenKeys$4;

    var OBJECT_ALREADY_INITIALIZED = 'Object already initialized';
    var TypeError$4 = globalThis$s.TypeError;
    var WeakMap$1 = globalThis$s.WeakMap;
    var set$2, get$1, has;

    var enforce = function (it) {
      return has(it) ? get$1(it) : set$2(it, {});
    };

    var getterFor = function (TYPE) {
      return function (it) {
        var state;
        if (!isObject$c(it) || (state = get$1(it)).type !== TYPE) {
          throw new TypeError$4('Incompatible receiver, ' + TYPE + ' required');
        } return state;
      };
    };

    if (NATIVE_WEAK_MAP || shared$1.state) {
      var store = shared$1.state || (shared$1.state = new WeakMap$1());
      /* eslint-disable no-self-assign -- prototype methods protection */
      store.get = store.get;
      store.has = store.has;
      store.set = store.set;
      /* eslint-enable no-self-assign -- prototype methods protection */
      set$2 = function (it, metadata) {
        if (store.has(it)) throw new TypeError$4(OBJECT_ALREADY_INITIALIZED);
        metadata.facade = it;
        store.set(it, metadata);
        return metadata;
      };
      get$1 = function (it) {
        return store.get(it) || {};
      };
      has = function (it) {
        return store.has(it);
      };
    } else {
      var STATE = sharedKey$2('state');
      hiddenKeys$3[STATE] = true;
      set$2 = function (it, metadata) {
        if (hasOwn$c(it, STATE)) throw new TypeError$4(OBJECT_ALREADY_INITIALIZED);
        metadata.facade = it;
        createNonEnumerableProperty$9(it, STATE, metadata);
        return metadata;
      };
      get$1 = function (it) {
        return hasOwn$c(it, STATE) ? it[STATE] : {};
      };
      has = function (it) {
        return hasOwn$c(it, STATE);
      };
    }

    var internalState = {
      set: set$2,
      get: get$1,
      has: has,
      enforce: enforce,
      getterFor: getterFor
    };

    var uncurryThis$z = functionUncurryThis;
    var fails$w = fails$C;
    var isCallable$h = isCallable$p;
    var hasOwn$b = hasOwnProperty_1;
    var DESCRIPTORS$g = descriptors;
    var CONFIGURABLE_FUNCTION_NAME$2 = functionName.CONFIGURABLE;
    var inspectSource$2 = inspectSource$3;
    var InternalStateModule$6 = internalState;

    var enforceInternalState$3 = InternalStateModule$6.enforce;
    var getInternalState$6 = InternalStateModule$6.get;
    var $String$3 = String;
    // eslint-disable-next-line es/no-object-defineproperty -- safe
    var defineProperty$7 = Object.defineProperty;
    var stringSlice$6 = uncurryThis$z(''.slice);
    var replace$4 = uncurryThis$z(''.replace);
    var join$1 = uncurryThis$z([].join);

    var CONFIGURABLE_LENGTH = DESCRIPTORS$g && !fails$w(function () {
      return defineProperty$7(function () { /* empty */ }, 'length', { value: 8 }).length !== 8;
    });

    var TEMPLATE = String(String).split('String');

    var makeBuiltIn$2 = makeBuiltIn$3.exports = function (value, name, options) {
      if (stringSlice$6($String$3(name), 0, 7) === 'Symbol(') {
        name = '[' + replace$4($String$3(name), /^Symbol\(([^)]*)\).*$/, '$1') + ']';
      }
      if (options && options.getter) name = 'get ' + name;
      if (options && options.setter) name = 'set ' + name;
      if (!hasOwn$b(value, 'name') || (CONFIGURABLE_FUNCTION_NAME$2 && value.name !== name)) {
        if (DESCRIPTORS$g) defineProperty$7(value, 'name', { value: name, configurable: true });
        else value.name = name;
      }
      if (CONFIGURABLE_LENGTH && options && hasOwn$b(options, 'arity') && value.length !== options.arity) {
        defineProperty$7(value, 'length', { value: options.arity });
      }
      try {
        if (options && hasOwn$b(options, 'constructor') && options.constructor) {
          if (DESCRIPTORS$g) defineProperty$7(value, 'prototype', { writable: false });
        // in V8 ~ Chrome 53, prototypes of some methods, like `Array.prototype.values`, are non-writable
        } else if (value.prototype) value.prototype = undefined;
      } catch (error) { /* empty */ }
      var state = enforceInternalState$3(value);
      if (!hasOwn$b(state, 'source')) {
        state.source = join$1(TEMPLATE, typeof name == 'string' ? name : '');
      } return value;
    };

    // add fake Function#toString for correct work wrapped methods / constructors with methods like LoDash isNative
    // eslint-disable-next-line no-extend-native -- required
    Function.prototype.toString = makeBuiltIn$2(function toString() {
      return isCallable$h(this) && getInternalState$6(this).source || inspectSource$2(this);
    }, 'toString');

    var isCallable$g = isCallable$p;
    var definePropertyModule$4 = objectDefineProperty;
    var makeBuiltIn$1 = makeBuiltIn$3.exports;
    var defineGlobalProperty$1 = defineGlobalProperty$3;

    var defineBuiltIn$b = function (O, key, value, options) {
      if (!options) options = {};
      var simple = options.enumerable;
      var name = options.name !== undefined ? options.name : key;
      if (isCallable$g(value)) makeBuiltIn$1(value, name, options);
      if (options.global) {
        if (simple) O[key] = value;
        else defineGlobalProperty$1(key, value);
      } else {
        try {
          if (!options.unsafe) delete O[key];
          else if (O[key]) simple = true;
        } catch (error) { /* empty */ }
        if (simple) O[key] = value;
        else definePropertyModule$4.f(O, key, {
          value: value,
          enumerable: false,
          configurable: !options.nonConfigurable,
          writable: !options.nonWritable
        });
      } return O;
    };

    var uncurryThis$y = functionUncurryThis;

    var toString$e = uncurryThis$y({}.toString);
    var stringSlice$5 = uncurryThis$y(''.slice);

    var classofRaw$2 = function (it) {
      return stringSlice$5(toString$e(it), 8, -1);
    };

    var TO_STRING_TAG_SUPPORT$2 = toStringTagSupport;
    var isCallable$f = isCallable$p;
    var classofRaw$1 = classofRaw$2;
    var wellKnownSymbol$k = wellKnownSymbol$n;

    var TO_STRING_TAG$2 = wellKnownSymbol$k('toStringTag');
    var $Object$2 = Object;

    // ES3 wrong here
    var CORRECT_ARGUMENTS = classofRaw$1(function () { return arguments; }()) === 'Arguments';

    // fallback for IE11 Script Access Denied error
    var tryGet = function (it, key) {
      try {
        return it[key];
      } catch (error) { /* empty */ }
    };

    // getting tag from ES6+ `Object.prototype.toString`
    var classof$f = TO_STRING_TAG_SUPPORT$2 ? classofRaw$1 : function (it) {
      var O, tag, result;
      return it === undefined ? 'Undefined' : it === null ? 'Null'
        // @@toStringTag case
        : typeof (tag = tryGet(O = $Object$2(it), TO_STRING_TAG$2)) == 'string' ? tag
        // builtinTag case
        : CORRECT_ARGUMENTS ? classofRaw$1(O)
        // ES3 arguments fallback
        : (result = classofRaw$1(O)) === 'Object' && isCallable$f(O.callee) ? 'Arguments' : result;
    };

    var TO_STRING_TAG_SUPPORT$1 = toStringTagSupport;
    var classof$e = classof$f;

    // `Object.prototype.toString` method implementation
    // https://tc39.es/ecma262/#sec-object.prototype.tostring
    var objectToString = TO_STRING_TAG_SUPPORT$1 ? {}.toString : function toString() {
      return '[object ' + classof$e(this) + ']';
    };

    var TO_STRING_TAG_SUPPORT = toStringTagSupport;
    var defineBuiltIn$a = defineBuiltIn$b;
    var toString$d = objectToString;

    // `Object.prototype.toString` method
    // https://tc39.es/ecma262/#sec-object.prototype.tostring
    if (!TO_STRING_TAG_SUPPORT) {
      defineBuiltIn$a(Object.prototype, 'toString', toString$d, { unsafe: true });
    }

    var classof$d = classof$f;

    var $String$2 = String;

    var toString$c = function (argument) {
      if (classof$d(argument) === 'Symbol') throw new TypeError('Cannot convert a Symbol value to a string');
      return $String$2(argument);
    };

    var anObject$e = anObject$g;

    // `RegExp.prototype.flags` getter implementation
    // https://tc39.es/ecma262/#sec-get-regexp.prototype.flags
    var regexpFlags$1 = function () {
      var that = anObject$e(this);
      var result = '';
      if (that.hasIndices) result += 'd';
      if (that.global) result += 'g';
      if (that.ignoreCase) result += 'i';
      if (that.multiline) result += 'm';
      if (that.dotAll) result += 's';
      if (that.unicode) result += 'u';
      if (that.unicodeSets) result += 'v';
      if (that.sticky) result += 'y';
      return result;
    };

    var call$m = functionCall;
    var hasOwn$a = hasOwnProperty_1;
    var isPrototypeOf$6 = objectIsPrototypeOf;
    var regExpFlags = regexpFlags$1;

    var RegExpPrototype$4 = RegExp.prototype;

    var regexpGetFlags = function (R) {
      var flags = R.flags;
      return flags === undefined && !('flags' in RegExpPrototype$4) && !hasOwn$a(R, 'flags') && isPrototypeOf$6(RegExpPrototype$4, R)
        ? call$m(regExpFlags, R) : flags;
    };

    var PROPER_FUNCTION_NAME$2 = functionName.PROPER;
    var defineBuiltIn$9 = defineBuiltIn$b;
    var anObject$d = anObject$g;
    var $toString = toString$c;
    var fails$v = fails$C;
    var getRegExpFlags$1 = regexpGetFlags;

    var TO_STRING = 'toString';
    var RegExpPrototype$3 = RegExp.prototype;
    var nativeToString = RegExpPrototype$3[TO_STRING];

    var NOT_GENERIC = fails$v(function () { return nativeToString.call({ source: 'a', flags: 'b' }) !== '/a/b'; });
    // FF44- RegExp#toString has a wrong name
    var INCORRECT_NAME = PROPER_FUNCTION_NAME$2 && nativeToString.name !== TO_STRING;

    // `RegExp.prototype.toString` method
    // https://tc39.es/ecma262/#sec-regexp.prototype.tostring
    if (NOT_GENERIC || INCORRECT_NAME) {
      defineBuiltIn$9(RegExpPrototype$3, TO_STRING, function toString() {
        var R = anObject$d(this);
        var pattern = $toString(R.source);
        var flags = $toString(getRegExpFlags$1(R));
        return '/' + pattern + '/' + flags;
      }, { unsafe: true });
    }

    var objectGetOwnPropertyDescriptor = {};

    var objectPropertyIsEnumerable = {};

    var $propertyIsEnumerable$1 = {}.propertyIsEnumerable;
    // eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe
    var getOwnPropertyDescriptor$6 = Object.getOwnPropertyDescriptor;

    // Nashorn ~ JDK8 bug
    var NASHORN_BUG = getOwnPropertyDescriptor$6 && !$propertyIsEnumerable$1.call({ 1: 2 }, 1);

    // `Object.prototype.propertyIsEnumerable` method implementation
    // https://tc39.es/ecma262/#sec-object.prototype.propertyisenumerable
    objectPropertyIsEnumerable.f = NASHORN_BUG ? function propertyIsEnumerable(V) {
      var descriptor = getOwnPropertyDescriptor$6(this, V);
      return !!descriptor && descriptor.enumerable;
    } : $propertyIsEnumerable$1;

    var uncurryThis$x = functionUncurryThis;
    var fails$u = fails$C;
    var classof$c = classofRaw$2;

    var $Object$1 = Object;
    var split = uncurryThis$x(''.split);

    // fallback for non-array-like ES3 and non-enumerable old V8 strings
    var indexedObject = fails$u(function () {
      // throws an error in rhino, see https://github.com/mozilla/rhino/issues/346
      // eslint-disable-next-line no-prototype-builtins -- safe
      return !$Object$1('z').propertyIsEnumerable(0);
    }) ? function (it) {
      return classof$c(it) === 'String' ? split(it, '') : $Object$1(it);
    } : $Object$1;

    // toObject with fallback for non-array-like ES3 strings
    var IndexedObject$4 = indexedObject;
    var requireObjectCoercible$7 = requireObjectCoercible$9;

    var toIndexedObject$a = function (it) {
      return IndexedObject$4(requireObjectCoercible$7(it));
    };

    var DESCRIPTORS$f = descriptors;
    var call$l = functionCall;
    var propertyIsEnumerableModule$1 = objectPropertyIsEnumerable;
    var createPropertyDescriptor$3 = createPropertyDescriptor$5;
    var toIndexedObject$9 = toIndexedObject$a;
    var toPropertyKey$1 = toPropertyKey$3;
    var hasOwn$9 = hasOwnProperty_1;
    var IE8_DOM_DEFINE = ie8DomDefine;

    // eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe
    var $getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;

    // `Object.getOwnPropertyDescriptor` method
    // https://tc39.es/ecma262/#sec-object.getownpropertydescriptor
    objectGetOwnPropertyDescriptor.f = DESCRIPTORS$f ? $getOwnPropertyDescriptor : function getOwnPropertyDescriptor(O, P) {
      O = toIndexedObject$9(O);
      P = toPropertyKey$1(P);
      if (IE8_DOM_DEFINE) try {
        return $getOwnPropertyDescriptor(O, P);
      } catch (error) { /* empty */ }
      if (hasOwn$9(O, P)) return createPropertyDescriptor$3(!call$l(propertyIsEnumerableModule$1.f, O, P), O[P]);
    };

    var objectGetOwnPropertyNames = {};

    var ceil = Math.ceil;
    var floor$4 = Math.floor;

    // `Math.trunc` method
    // https://tc39.es/ecma262/#sec-math.trunc
    // eslint-disable-next-line es/no-math-trunc -- safe
    var mathTrunc = Math.trunc || function trunc(x) {
      var n = +x;
      return (n > 0 ? floor$4 : ceil)(n);
    };

    var trunc = mathTrunc;

    // `ToIntegerOrInfinity` abstract operation
    // https://tc39.es/ecma262/#sec-tointegerorinfinity
    var toIntegerOrInfinity$9 = function (argument) {
      var number = +argument;
      // eslint-disable-next-line no-self-compare -- NaN check
      return number !== number || number === 0 ? 0 : trunc(number);
    };

    var toIntegerOrInfinity$8 = toIntegerOrInfinity$9;

    var max$2 = Math.max;
    var min$6 = Math.min;

    // Helper for a popular repeating case of the spec:
    // Let integer be ? ToInteger(index).
    // If integer < 0, let result be max((length + integer), 0); else let result be min(integer, length).
    var toAbsoluteIndex$7 = function (index, length) {
      var integer = toIntegerOrInfinity$8(index);
      return integer < 0 ? max$2(integer + length, 0) : min$6(integer, length);
    };

    var toIntegerOrInfinity$7 = toIntegerOrInfinity$9;

    var min$5 = Math.min;

    // `ToLength` abstract operation
    // https://tc39.es/ecma262/#sec-tolength
    var toLength$9 = function (argument) {
      var len = toIntegerOrInfinity$7(argument);
      return len > 0 ? min$5(len, 0x1FFFFFFFFFFFFF) : 0; // 2 ** 53 - 1 == 9007199254740991
    };

    var toLength$8 = toLength$9;

    // `LengthOfArrayLike` abstract operation
    // https://tc39.es/ecma262/#sec-lengthofarraylike
    var lengthOfArrayLike$e = function (obj) {
      return toLength$8(obj.length);
    };

    var toIndexedObject$8 = toIndexedObject$a;
    var toAbsoluteIndex$6 = toAbsoluteIndex$7;
    var lengthOfArrayLike$d = lengthOfArrayLike$e;

    // `Array.prototype.{ indexOf, includes }` methods implementation
    var createMethod$5 = function (IS_INCLUDES) {
      return function ($this, el, fromIndex) {
        var O = toIndexedObject$8($this);
        var length = lengthOfArrayLike$d(O);
        if (length === 0) return !IS_INCLUDES && -1;
        var index = toAbsoluteIndex$6(fromIndex, length);
        var value;
        // Array#includes uses SameValueZero equality algorithm
        // eslint-disable-next-line no-self-compare -- NaN check
        if (IS_INCLUDES && el !== el) while (length > index) {
          value = O[index++];
          // eslint-disable-next-line no-self-compare -- NaN check
          if (value !== value) return true;
        // Array#indexOf ignores holes, Array#includes - not
        } else for (;length > index; index++) {
          if ((IS_INCLUDES || index in O) && O[index] === el) return IS_INCLUDES || index || 0;
        } return !IS_INCLUDES && -1;
      };
    };

    var arrayIncludes = {
      // `Array.prototype.includes` method
      // https://tc39.es/ecma262/#sec-array.prototype.includes
      includes: createMethod$5(true),
      // `Array.prototype.indexOf` method
      // https://tc39.es/ecma262/#sec-array.prototype.indexof
      indexOf: createMethod$5(false)
    };

    var uncurryThis$w = functionUncurryThis;
    var hasOwn$8 = hasOwnProperty_1;
    var toIndexedObject$7 = toIndexedObject$a;
    var indexOf$1 = arrayIncludes.indexOf;
    var hiddenKeys$2 = hiddenKeys$4;

    var push$3 = uncurryThis$w([].push);

    var objectKeysInternal = function (object, names) {
      var O = toIndexedObject$7(object);
      var i = 0;
      var result = [];
      var key;
      for (key in O) !hasOwn$8(hiddenKeys$2, key) && hasOwn$8(O, key) && push$3(result, key);
      // Don't enum bug & hidden keys
      while (names.length > i) if (hasOwn$8(O, key = names[i++])) {
        ~indexOf$1(result, key) || push$3(result, key);
      }
      return result;
    };

    // IE8- don't enum bug keys
    var enumBugKeys$3 = [
      'constructor',
      'hasOwnProperty',
      'isPrototypeOf',
      'propertyIsEnumerable',
      'toLocaleString',
      'toString',
      'valueOf'
    ];

    var internalObjectKeys$1 = objectKeysInternal;
    var enumBugKeys$2 = enumBugKeys$3;

    var hiddenKeys$1 = enumBugKeys$2.concat('length', 'prototype');

    // `Object.getOwnPropertyNames` method
    // https://tc39.es/ecma262/#sec-object.getownpropertynames
    // eslint-disable-next-line es/no-object-getownpropertynames -- safe
    objectGetOwnPropertyNames.f = Object.getOwnPropertyNames || function getOwnPropertyNames(O) {
      return internalObjectKeys$1(O, hiddenKeys$1);
    };

    var objectGetOwnPropertySymbols = {};

    // eslint-disable-next-line es/no-object-getownpropertysymbols -- safe
    objectGetOwnPropertySymbols.f = Object.getOwnPropertySymbols;

    var getBuiltIn$6 = getBuiltIn$8;
    var uncurryThis$v = functionUncurryThis;
    var getOwnPropertyNamesModule = objectGetOwnPropertyNames;
    var getOwnPropertySymbolsModule$1 = objectGetOwnPropertySymbols;
    var anObject$c = anObject$g;

    var concat$1 = uncurryThis$v([].concat);

    // all object keys, includes non-enumerable and symbols
    var ownKeys$1 = getBuiltIn$6('Reflect', 'ownKeys') || function ownKeys(it) {
      var keys = getOwnPropertyNamesModule.f(anObject$c(it));
      var getOwnPropertySymbols = getOwnPropertySymbolsModule$1.f;
      return getOwnPropertySymbols ? concat$1(keys, getOwnPropertySymbols(it)) : keys;
    };

    var hasOwn$7 = hasOwnProperty_1;
    var ownKeys = ownKeys$1;
    var getOwnPropertyDescriptorModule$1 = objectGetOwnPropertyDescriptor;
    var definePropertyModule$3 = objectDefineProperty;

    var copyConstructorProperties$3 = function (target, source, exceptions) {
      var keys = ownKeys(source);
      var defineProperty = definePropertyModule$3.f;
      var getOwnPropertyDescriptor = getOwnPropertyDescriptorModule$1.f;
      for (var i = 0; i < keys.length; i++) {
        var key = keys[i];
        if (!hasOwn$7(target, key) && !(exceptions && hasOwn$7(exceptions, key))) {
          defineProperty(target, key, getOwnPropertyDescriptor(source, key));
        }
      }
    };

    var fails$t = fails$C;
    var isCallable$e = isCallable$p;

    var replacement = /#|\.prototype\./;

    var isForced$4 = function (feature, detection) {
      var value = data[normalize(feature)];
      return value === POLYFILL ? true
        : value === NATIVE ? false
        : isCallable$e(detection) ? fails$t(detection)
        : !!detection;
    };

    var normalize = isForced$4.normalize = function (string) {
      return String(string).replace(replacement, '.').toLowerCase();
    };

    var data = isForced$4.data = {};
    var NATIVE = isForced$4.NATIVE = 'N';
    var POLYFILL = isForced$4.POLYFILL = 'P';

    var isForced_1 = isForced$4;

    var globalThis$r = globalThis_1;
    var getOwnPropertyDescriptor$5 = objectGetOwnPropertyDescriptor.f;
    var createNonEnumerableProperty$8 = createNonEnumerableProperty$a;
    var defineBuiltIn$8 = defineBuiltIn$b;
    var defineGlobalProperty = defineGlobalProperty$3;
    var copyConstructorProperties$2 = copyConstructorProperties$3;
    var isForced$3 = isForced_1;

    /*
      options.target         - name of the target object
      options.global         - target is the global object
      options.stat           - export as static methods of target
      options.proto          - export as prototype methods of target
      options.real           - real prototype method for the `pure` version
      options.forced         - export even if the native feature is available
      options.bind           - bind methods to the target, required for the `pure` version
      options.wrap           - wrap constructors to preventing global pollution, required for the `pure` version
      options.unsafe         - use the simple assignment of property instead of delete + defineProperty
      options.sham           - add a flag to not completely full polyfills
      options.enumerable     - export as enumerable property
      options.dontCallGetSet - prevent calling a getter on target
      options.name           - the .name of the function if it does not match the key
    */
    var _export = function (options, source) {
      var TARGET = options.target;
      var GLOBAL = options.global;
      var STATIC = options.stat;
      var FORCED, target, key, targetProperty, sourceProperty, descriptor;
      if (GLOBAL) {
        target = globalThis$r;
      } else if (STATIC) {
        target = globalThis$r[TARGET] || defineGlobalProperty(TARGET, {});
      } else {
        target = globalThis$r[TARGET] && globalThis$r[TARGET].prototype;
      }
      if (target) for (key in source) {
        sourceProperty = source[key];
        if (options.dontCallGetSet) {
          descriptor = getOwnPropertyDescriptor$5(target, key);
          targetProperty = descriptor && descriptor.value;
        } else targetProperty = target[key];
        FORCED = isForced$3(GLOBAL ? key : TARGET + (STATIC ? '.' : '#') + key, options.forced);
        // contained in target
        if (!FORCED && targetProperty !== undefined) {
          if (typeof sourceProperty == typeof targetProperty) continue;
          copyConstructorProperties$2(sourceProperty, targetProperty);
        }
        // add a flag to not completely full polyfills
        if (options.sham || (targetProperty && targetProperty.sham)) {
          createNonEnumerableProperty$8(sourceProperty, 'sham', true);
        }
        defineBuiltIn$8(target, key, sourceProperty, options);
      }
    };

    var $$A = _export;

    // `Number.MAX_SAFE_INTEGER` constant
    // https://tc39.es/ecma262/#sec-number.max_safe_integer
    $$A({ target: 'Number', stat: true, nonConfigurable: true, nonWritable: true }, {
      MAX_SAFE_INTEGER: 0x1FFFFFFFFFFFFF
    });

    var globalThis$q = globalThis_1;

    var path$1 = globalThis$q;

    var uncurryThis$u = functionUncurryThis;
    var aCallable$8 = aCallable$a;

    var functionUncurryThisAccessor = function (object, key, method) {
      try {
        // eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe
        return uncurryThis$u(aCallable$8(Object.getOwnPropertyDescriptor(object, key)[method]));
      } catch (error) { /* empty */ }
    };

    var isObject$b = isObject$h;

    var isPossiblePrototype$1 = function (argument) {
      return isObject$b(argument) || argument === null;
    };

    var isPossiblePrototype = isPossiblePrototype$1;

    var $String$1 = String;
    var $TypeError$e = TypeError;

    var aPossiblePrototype$1 = function (argument) {
      if (isPossiblePrototype(argument)) return argument;
      throw new $TypeError$e("Can't set " + $String$1(argument) + ' as a prototype');
    };

    /* eslint-disable no-proto -- safe */
    var uncurryThisAccessor = functionUncurryThisAccessor;
    var isObject$a = isObject$h;
    var requireObjectCoercible$6 = requireObjectCoercible$9;
    var aPossiblePrototype = aPossiblePrototype$1;

    // `Object.setPrototypeOf` method
    // https://tc39.es/ecma262/#sec-object.setprototypeof
    // Works with __proto__ only. Old v8 can't work with null proto objects.
    // eslint-disable-next-line es/no-object-setprototypeof -- safe
    var objectSetPrototypeOf = Object.setPrototypeOf || ('__proto__' in {} ? function () {
      var CORRECT_SETTER = false;
      var test = {};
      var setter;
      try {
        setter = uncurryThisAccessor(Object.prototype, '__proto__', 'set');
        setter(test, []);
        CORRECT_SETTER = test instanceof Array;
      } catch (error) { /* empty */ }
      return function setPrototypeOf(O, proto) {
        requireObjectCoercible$6(O);
        aPossiblePrototype(proto);
        if (!isObject$a(O)) return O;
        if (CORRECT_SETTER) setter(O, proto);
        else O.__proto__ = proto;
        return O;
      };
    }() : undefined);

    var isCallable$d = isCallable$p;
    var isObject$9 = isObject$h;
    var setPrototypeOf$5 = objectSetPrototypeOf;

    // makes subclassing work correct for wrapped built-ins
    var inheritIfRequired$4 = function ($this, dummy, Wrapper) {
      var NewTarget, NewTargetPrototype;
      if (
        // it can work only with native `setPrototypeOf`
        setPrototypeOf$5 &&
        // we haven't completely correct pre-ES6 way for getting `new.target`, so use this
        isCallable$d(NewTarget = dummy.constructor) &&
        NewTarget !== Wrapper &&
        isObject$9(NewTargetPrototype = NewTarget.prototype) &&
        NewTargetPrototype !== Wrapper.prototype
      ) setPrototypeOf$5($this, NewTargetPrototype);
      return $this;
    };

    var uncurryThis$t = functionUncurryThis;

    // `thisNumberValue` abstract operation
    // https://tc39.es/ecma262/#sec-thisnumbervalue
    var thisNumberValue$1 = uncurryThis$t(1.0.valueOf);

    // a string of all valid unicode whitespaces
    var whitespaces$2 = '\u0009\u000A\u000B\u000C\u000D\u0020\u00A0\u1680\u2000\u2001\u2002' +
      '\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF';

    var uncurryThis$s = functionUncurryThis;
    var requireObjectCoercible$5 = requireObjectCoercible$9;
    var toString$b = toString$c;
    var whitespaces$1 = whitespaces$2;

    var replace$3 = uncurryThis$s(''.replace);
    var ltrim = RegExp('^[' + whitespaces$1 + ']+');
    var rtrim = RegExp('(^|[^' + whitespaces$1 + '])[' + whitespaces$1 + ']+$');

    // `String.prototype.{ trim, trimStart, trimEnd, trimLeft, trimRight }` methods implementation
    var createMethod$4 = function (TYPE) {
      return function ($this) {
        var string = toString$b(requireObjectCoercible$5($this));
        if (TYPE & 1) string = replace$3(string, ltrim, '');
        if (TYPE & 2) string = replace$3(string, rtrim, '$1');
        return string;
      };
    };

    var stringTrim = {
      // `String.prototype.{ trimLeft, trimStart }` methods
      // https://tc39.es/ecma262/#sec-string.prototype.trimstart
      start: createMethod$4(1),
      // `String.prototype.{ trimRight, trimEnd }` methods
      // https://tc39.es/ecma262/#sec-string.prototype.trimend
      end: createMethod$4(2),
      // `String.prototype.trim` method
      // https://tc39.es/ecma262/#sec-string.prototype.trim
      trim: createMethod$4(3)
    };

    var $$z = _export;
    var IS_PURE = isPure;
    var DESCRIPTORS$e = descriptors;
    var globalThis$p = globalThis_1;
    var path = path$1;
    var uncurryThis$r = functionUncurryThis;
    var isForced$2 = isForced_1;
    var hasOwn$6 = hasOwnProperty_1;
    var inheritIfRequired$3 = inheritIfRequired$4;
    var isPrototypeOf$5 = objectIsPrototypeOf;
    var isSymbol$2 = isSymbol$5;
    var toPrimitive$1 = toPrimitive$3;
    var fails$s = fails$C;
    var getOwnPropertyNames$2 = objectGetOwnPropertyNames.f;
    var getOwnPropertyDescriptor$4 = objectGetOwnPropertyDescriptor.f;
    var defineProperty$6 = objectDefineProperty.f;
    var thisNumberValue = thisNumberValue$1;
    var trim$1 = stringTrim.trim;

    var NUMBER = 'Number';
    var NativeNumber = globalThis$p[NUMBER];
    path[NUMBER];
    var NumberPrototype = NativeNumber.prototype;
    var TypeError$3 = globalThis$p.TypeError;
    var stringSlice$4 = uncurryThis$r(''.slice);
    var charCodeAt$2 = uncurryThis$r(''.charCodeAt);

    // `ToNumeric` abstract operation
    // https://tc39.es/ecma262/#sec-tonumeric
    var toNumeric = function (value) {
      var primValue = toPrimitive$1(value, 'number');
      return typeof primValue == 'bigint' ? primValue : toNumber(primValue);
    };

    // `ToNumber` abstract operation
    // https://tc39.es/ecma262/#sec-tonumber
    var toNumber = function (argument) {
      var it = toPrimitive$1(argument, 'number');
      var first, third, radix, maxCode, digits, length, index, code;
      if (isSymbol$2(it)) throw new TypeError$3('Cannot convert a Symbol value to a number');
      if (typeof it == 'string' && it.length > 2) {
        it = trim$1(it);
        first = charCodeAt$2(it, 0);
        if (first === 43 || first === 45) {
          third = charCodeAt$2(it, 2);
          if (third === 88 || third === 120) return NaN; // Number('+0x1') should be NaN, old V8 fix
        } else if (first === 48) {
          switch (charCodeAt$2(it, 1)) {
            // fast equal of /^0b[01]+$/i
            case 66:
            case 98:
              radix = 2;
              maxCode = 49;
              break;
            // fast equal of /^0o[0-7]+$/i
            case 79:
            case 111:
              radix = 8;
              maxCode = 55;
              break;
            default:
              return +it;
          }
          digits = stringSlice$4(it, 2);
          length = digits.length;
          for (index = 0; index < length; index++) {
            code = charCodeAt$2(digits, index);
            // parseInt parses a string to a first unavailable symbol
            // but ToNumber should return NaN if a string contains unavailable symbols
            if (code < 48 || code > maxCode) return NaN;
          } return parseInt(digits, radix);
        }
      } return +it;
    };

    var FORCED$6 = isForced$2(NUMBER, !NativeNumber(' 0o1') || !NativeNumber('0b1') || NativeNumber('+0x1'));

    var calledWithNew = function (dummy) {
      // includes check on 1..constructor(foo) case
      return isPrototypeOf$5(NumberPrototype, dummy) && fails$s(function () { thisNumberValue(dummy); });
    };

    // `Number` constructor
    // https://tc39.es/ecma262/#sec-number-constructor
    var NumberWrapper = function Number(value) {
      var n = arguments.length < 1 ? 0 : NativeNumber(toNumeric(value));
      return calledWithNew(this) ? inheritIfRequired$3(Object(n), this, NumberWrapper) : n;
    };

    NumberWrapper.prototype = NumberPrototype;
    if (FORCED$6 && !IS_PURE) NumberPrototype.constructor = NumberWrapper;

    $$z({ global: true, constructor: true, wrap: true, forced: FORCED$6 }, {
      Number: NumberWrapper
    });

    // Use `internal/copy-constructor-properties` helper in `core-js@4`
    var copyConstructorProperties$1 = function (target, source) {
      for (var keys = DESCRIPTORS$e ? getOwnPropertyNames$2(source) : (
        // ES3:
        'MAX_VALUE,MIN_VALUE,NaN,NEGATIVE_INFINITY,POSITIVE_INFINITY,' +
        // ES2015 (in case, if modules with ES2015 Number statics required before):
        'EPSILON,MAX_SAFE_INTEGER,MIN_SAFE_INTEGER,isFinite,isInteger,isNaN,isSafeInteger,parseFloat,parseInt,' +
        // ESNext
        'fromString,range'
      ).split(','), j = 0, key; keys.length > j; j++) {
        if (hasOwn$6(source, key = keys[j]) && !hasOwn$6(target, key)) {
          defineProperty$6(target, key, getOwnPropertyDescriptor$4(source, key));
        }
      }
    };
    if (FORCED$6 || IS_PURE) copyConstructorProperties$1(path[NUMBER], NativeNumber);

    var fails$r = fails$C;
    var globalThis$o = globalThis_1;

    // babel-minify and Closure Compiler transpiles RegExp('a', 'y') -> /a/y and it causes SyntaxError
    var $RegExp$2 = globalThis$o.RegExp;

    var UNSUPPORTED_Y$2 = fails$r(function () {
      var re = $RegExp$2('a', 'y');
      re.lastIndex = 2;
      return re.exec('abcd') !== null;
    });

    // UC Browser bug
    // https://github.com/zloirock/core-js/issues/1008
    var MISSED_STICKY$2 = UNSUPPORTED_Y$2 || fails$r(function () {
      return !$RegExp$2('a', 'y').sticky;
    });

    var BROKEN_CARET = UNSUPPORTED_Y$2 || fails$r(function () {
      // https://bugzilla.mozilla.org/show_bug.cgi?id=773687
      var re = $RegExp$2('^r', 'gy');
      re.lastIndex = 2;
      return re.exec('str') !== null;
    });

    var regexpStickyHelpers = {
      BROKEN_CARET: BROKEN_CARET,
      MISSED_STICKY: MISSED_STICKY$2,
      UNSUPPORTED_Y: UNSUPPORTED_Y$2
    };

    var objectDefineProperties = {};

    var internalObjectKeys = objectKeysInternal;
    var enumBugKeys$1 = enumBugKeys$3;

    // `Object.keys` method
    // https://tc39.es/ecma262/#sec-object.keys
    // eslint-disable-next-line es/no-object-keys -- safe
    var objectKeys$3 = Object.keys || function keys(O) {
      return internalObjectKeys(O, enumBugKeys$1);
    };

    var DESCRIPTORS$d = descriptors;
    var V8_PROTOTYPE_DEFINE_BUG = v8PrototypeDefineBug;
    var definePropertyModule$2 = objectDefineProperty;
    var anObject$b = anObject$g;
    var toIndexedObject$6 = toIndexedObject$a;
    var objectKeys$2 = objectKeys$3;

    // `Object.defineProperties` method
    // https://tc39.es/ecma262/#sec-object.defineproperties
    // eslint-disable-next-line es/no-object-defineproperties -- safe
    objectDefineProperties.f = DESCRIPTORS$d && !V8_PROTOTYPE_DEFINE_BUG ? Object.defineProperties : function defineProperties(O, Properties) {
      anObject$b(O);
      var props = toIndexedObject$6(Properties);
      var keys = objectKeys$2(Properties);
      var length = keys.length;
      var index = 0;
      var key;
      while (length > index) definePropertyModule$2.f(O, key = keys[index++], props[key]);
      return O;
    };

    var getBuiltIn$5 = getBuiltIn$8;

    var html$2 = getBuiltIn$5('document', 'documentElement');

    /* global ActiveXObject -- old IE, WSH */
    var anObject$a = anObject$g;
    var definePropertiesModule = objectDefineProperties;
    var enumBugKeys = enumBugKeys$3;
    var hiddenKeys = hiddenKeys$4;
    var html$1 = html$2;
    var documentCreateElement$1 = documentCreateElement$2;
    var sharedKey$1 = sharedKey$3;

    var GT = '>';
    var LT = '<';
    var PROTOTYPE$1 = 'prototype';
    var SCRIPT = 'script';
    var IE_PROTO$1 = sharedKey$1('IE_PROTO');

    var EmptyConstructor = function () { /* empty */ };

    var scriptTag = function (content) {
      return LT + SCRIPT + GT + content + LT + '/' + SCRIPT + GT;
    };

    // Create object with fake `null` prototype: use ActiveX Object with cleared prototype
    var NullProtoObjectViaActiveX = function (activeXDocument) {
      activeXDocument.write(scriptTag(''));
      activeXDocument.close();
      var temp = activeXDocument.parentWindow.Object;
      // eslint-disable-next-line no-useless-assignment -- avoid memory leak
      activeXDocument = null;
      return temp;
    };

    // Create object with fake `null` prototype: use iframe Object with cleared prototype
    var NullProtoObjectViaIFrame = function () {
      // Thrash, waste and sodomy: IE GC bug
      var iframe = documentCreateElement$1('iframe');
      var JS = 'java' + SCRIPT + ':';
      var iframeDocument;
      iframe.style.display = 'none';
      html$1.appendChild(iframe);
      // https://github.com/zloirock/core-js/issues/475
      iframe.src = String(JS);
      iframeDocument = iframe.contentWindow.document;
      iframeDocument.open();
      iframeDocument.write(scriptTag('document.F=Object'));
      iframeDocument.close();
      return iframeDocument.F;
    };

    // Check for document.domain and active x support
    // No need to use active x approach when document.domain is not set
    // see https://github.com/es-shims/es5-shim/issues/150
    // variation of https://github.com/kitcambridge/es5-shim/commit/4f738ac066346
    // avoid IE GC bug
    var activeXDocument;
    var NullProtoObject = function () {
      try {
        activeXDocument = new ActiveXObject('htmlfile');
      } catch (error) { /* ignore */ }
      NullProtoObject = typeof document != 'undefined'
        ? document.domain && activeXDocument
          ? NullProtoObjectViaActiveX(activeXDocument) // old IE
          : NullProtoObjectViaIFrame()
        : NullProtoObjectViaActiveX(activeXDocument); // WSH
      var length = enumBugKeys.length;
      while (length--) delete NullProtoObject[PROTOTYPE$1][enumBugKeys[length]];
      return NullProtoObject();
    };

    hiddenKeys[IE_PROTO$1] = true;

    // `Object.create` method
    // https://tc39.es/ecma262/#sec-object.create
    // eslint-disable-next-line es/no-object-create -- safe
    var objectCreate = Object.create || function create(O, Properties) {
      var result;
      if (O !== null) {
        EmptyConstructor[PROTOTYPE$1] = anObject$a(O);
        result = new EmptyConstructor();
        EmptyConstructor[PROTOTYPE$1] = null;
        // add "__proto__" for Object.getPrototypeOf polyfill
        result[IE_PROTO$1] = O;
      } else result = NullProtoObject();
      return Properties === undefined ? result : definePropertiesModule.f(result, Properties);
    };

    var fails$q = fails$C;
    var globalThis$n = globalThis_1;

    // babel-minify and Closure Compiler transpiles RegExp('.', 's') -> /./s and it causes SyntaxError
    var $RegExp$1 = globalThis$n.RegExp;

    var regexpUnsupportedDotAll = fails$q(function () {
      var re = $RegExp$1('.', 's');
      return !(re.dotAll && re.test('\n') && re.flags === 's');
    });

    var fails$p = fails$C;
    var globalThis$m = globalThis_1;

    // babel-minify and Closure Compiler transpiles RegExp('(?<a>b)', 'g') -> /(?<a>b)/g and it causes SyntaxError
    var $RegExp = globalThis$m.RegExp;

    var regexpUnsupportedNcg = fails$p(function () {
      var re = $RegExp('(?<a>b)', 'g');
      return re.exec('b').groups.a !== 'b' ||
        'b'.replace(re, '$<a>c') !== 'bc';
    });

    /* eslint-disable regexp/no-empty-capturing-group, regexp/no-empty-group, regexp/no-lazy-ends -- testing */
    /* eslint-disable regexp/no-useless-quantifier -- testing */
    var call$k = functionCall;
    var uncurryThis$q = functionUncurryThis;
    var toString$a = toString$c;
    var regexpFlags = regexpFlags$1;
    var stickyHelpers$1 = regexpStickyHelpers;
    var shared = shared$4;
    var create$4 = objectCreate;
    var getInternalState$5 = internalState.get;
    var UNSUPPORTED_DOT_ALL$1 = regexpUnsupportedDotAll;
    var UNSUPPORTED_NCG$1 = regexpUnsupportedNcg;

    var nativeReplace = shared('native-string-replace', String.prototype.replace);
    var nativeExec = RegExp.prototype.exec;
    var patchedExec = nativeExec;
    var charAt$5 = uncurryThis$q(''.charAt);
    var indexOf = uncurryThis$q(''.indexOf);
    var replace$2 = uncurryThis$q(''.replace);
    var stringSlice$3 = uncurryThis$q(''.slice);

    var UPDATES_LAST_INDEX_WRONG = (function () {
      var re1 = /a/;
      var re2 = /b*/g;
      call$k(nativeExec, re1, 'a');
      call$k(nativeExec, re2, 'a');
      return re1.lastIndex !== 0 || re2.lastIndex !== 0;
    })();

    var UNSUPPORTED_Y$1 = stickyHelpers$1.BROKEN_CARET;

    // nonparticipating capturing group, copied from es5-shim's String#split patch.
    var NPCG_INCLUDED = /()??/.exec('')[1] !== undefined;

    var PATCH = UPDATES_LAST_INDEX_WRONG || NPCG_INCLUDED || UNSUPPORTED_Y$1 || UNSUPPORTED_DOT_ALL$1 || UNSUPPORTED_NCG$1;

    if (PATCH) {
      patchedExec = function exec(string) {
        var re = this;
        var state = getInternalState$5(re);
        var str = toString$a(string);
        var raw = state.raw;
        var result, reCopy, lastIndex, match, i, object, group;

        if (raw) {
          raw.lastIndex = re.lastIndex;
          result = call$k(patchedExec, raw, str);
          re.lastIndex = raw.lastIndex;
          return result;
        }

        var groups = state.groups;
        var sticky = UNSUPPORTED_Y$1 && re.sticky;
        var flags = call$k(regexpFlags, re);
        var source = re.source;
        var charsAdded = 0;
        var strCopy = str;

        if (sticky) {
          flags = replace$2(flags, 'y', '');
          if (indexOf(flags, 'g') === -1) {
            flags += 'g';
          }

          strCopy = stringSlice$3(str, re.lastIndex);
          // Support anchored sticky behavior.
          if (re.lastIndex > 0 && (!re.multiline || re.multiline && charAt$5(str, re.lastIndex - 1) !== '\n')) {
            source = '(?: ' + source + ')';
            strCopy = ' ' + strCopy;
            charsAdded++;
          }
          // ^(? + rx + ) is needed, in combination with some str slicing, to
          // simulate the 'y' flag.
          reCopy = new RegExp('^(?:' + source + ')', flags);
        }

        if (NPCG_INCLUDED) {
          reCopy = new RegExp('^' + source + '$(?!\\s)', flags);
        }
        if (UPDATES_LAST_INDEX_WRONG) lastIndex = re.lastIndex;

        match = call$k(nativeExec, sticky ? reCopy : re, strCopy);

        if (sticky) {
          if (match) {
            match.input = stringSlice$3(match.input, charsAdded);
            match[0] = stringSlice$3(match[0], charsAdded);
            match.index = re.lastIndex;
            re.lastIndex += match[0].length;
          } else re.lastIndex = 0;
        } else if (UPDATES_LAST_INDEX_WRONG && match) {
          re.lastIndex = re.global ? match.index + match[0].length : lastIndex;
        }
        if (NPCG_INCLUDED && match && match.length > 1) {
          // Fix browsers whose `exec` methods don't consistently return `undefined`
          // for NPCG, like IE8. NOTE: This doesn't work for /(.?)?/
          call$k(nativeReplace, match[0], reCopy, function () {
            for (i = 1; i < arguments.length - 2; i++) {
              if (arguments[i] === undefined) match[i] = undefined;
            }
          });
        }

        if (match && groups) {
          match.groups = object = create$4(null);
          for (i = 0; i < groups.length; i++) {
            group = groups[i];
            object[group[0]] = match[group[1]];
          }
        }

        return match;
      };
    }

    var regexpExec$2 = patchedExec;

    var $$y = _export;
    var exec$4 = regexpExec$2;

    // `RegExp.prototype.exec` method
    // https://tc39.es/ecma262/#sec-regexp.prototype.exec
    $$y({ target: 'RegExp', proto: true, forced: /./.exec !== exec$4 }, {
      exec: exec$4
    });

    // TODO: Remove from `core-js@4` since it's moved to entry points

    var $$x = _export;
    var call$j = functionCall;
    var isCallable$c = isCallable$p;
    var anObject$9 = anObject$g;
    var toString$9 = toString$c;

    var DELEGATES_TO_EXEC = function () {
      var execCalled = false;
      var re = /[ac]/;
      re.exec = function () {
        execCalled = true;
        return /./.exec.apply(this, arguments);
      };
      return re.test('abc') === true && execCalled;
    }();

    var nativeTest = /./.test;

    // `RegExp.prototype.test` method
    // https://tc39.es/ecma262/#sec-regexp.prototype.test
    $$x({ target: 'RegExp', proto: true, forced: !DELEGATES_TO_EXEC }, {
      test: function (S) {
        var R = anObject$9(this);
        var string = toString$9(S);
        var exec = R.exec;
        if (!isCallable$c(exec)) return call$j(nativeTest, R, string);
        var result = call$j(exec, R, string);
        if (result === null) return false;
        anObject$9(result);
        return true;
      }
    });

    var wellKnownSymbol$j = wellKnownSymbol$n;
    var create$3 = objectCreate;
    var defineProperty$5 = objectDefineProperty.f;

    var UNSCOPABLES = wellKnownSymbol$j('unscopables');
    var ArrayPrototype$1 = Array.prototype;

    // Array.prototype[@@unscopables]
    // https://tc39.es/ecma262/#sec-array.prototype-@@unscopables
    if (ArrayPrototype$1[UNSCOPABLES] === undefined) {
      defineProperty$5(ArrayPrototype$1, UNSCOPABLES, {
        configurable: true,
        value: create$3(null)
      });
    }

    // add a key to Array.prototype[@@unscopables]
    var addToUnscopables$4 = function (key) {
      ArrayPrototype$1[UNSCOPABLES][key] = true;
    };

    var iterators = {};

    var fails$o = fails$C;

    var correctPrototypeGetter = !fails$o(function () {
      function F() { /* empty */ }
      F.prototype.constructor = null;
      // eslint-disable-next-line es/no-object-getprototypeof -- required for testing
      return Object.getPrototypeOf(new F()) !== F.prototype;
    });

    var hasOwn$5 = hasOwnProperty_1;
    var isCallable$b = isCallable$p;
    var toObject$a = toObject$c;
    var sharedKey = sharedKey$3;
    var CORRECT_PROTOTYPE_GETTER$1 = correctPrototypeGetter;

    var IE_PROTO = sharedKey('IE_PROTO');
    var $Object = Object;
    var ObjectPrototype$2 = $Object.prototype;

    // `Object.getPrototypeOf` method
    // https://tc39.es/ecma262/#sec-object.getprototypeof
    // eslint-disable-next-line es/no-object-getprototypeof -- safe
    var objectGetPrototypeOf$1 = CORRECT_PROTOTYPE_GETTER$1 ? $Object.getPrototypeOf : function (O) {
      var object = toObject$a(O);
      if (hasOwn$5(object, IE_PROTO)) return object[IE_PROTO];
      var constructor = object.constructor;
      if (isCallable$b(constructor) && object instanceof constructor) {
        return constructor.prototype;
      } return object instanceof $Object ? ObjectPrototype$2 : null;
    };

    var fails$n = fails$C;
    var isCallable$a = isCallable$p;
    var isObject$8 = isObject$h;
    var getPrototypeOf$3 = objectGetPrototypeOf$1;
    var defineBuiltIn$7 = defineBuiltIn$b;
    var wellKnownSymbol$i = wellKnownSymbol$n;

    var ITERATOR$7 = wellKnownSymbol$i('iterator');
    var BUGGY_SAFARI_ITERATORS$1 = false;

    // `%IteratorPrototype%` object
    // https://tc39.es/ecma262/#sec-%iteratorprototype%-object
    var IteratorPrototype$2, PrototypeOfArrayIteratorPrototype, arrayIterator;

    /* eslint-disable es/no-array-prototype-keys -- safe */
    if ([].keys) {
      arrayIterator = [].keys();
      // Safari 8 has buggy iterators w/o `next`
      if (!('next' in arrayIterator)) BUGGY_SAFARI_ITERATORS$1 = true;
      else {
        PrototypeOfArrayIteratorPrototype = getPrototypeOf$3(getPrototypeOf$3(arrayIterator));
        if (PrototypeOfArrayIteratorPrototype !== Object.prototype) IteratorPrototype$2 = PrototypeOfArrayIteratorPrototype;
      }
    }

    var NEW_ITERATOR_PROTOTYPE = !isObject$8(IteratorPrototype$2) || fails$n(function () {
      var test = {};
      // FF44- legacy iterators case
      return IteratorPrototype$2[ITERATOR$7].call(test) !== test;
    });

    if (NEW_ITERATOR_PROTOTYPE) IteratorPrototype$2 = {};

    // `%IteratorPrototype%[@@iterator]()` method
    // https://tc39.es/ecma262/#sec-%iteratorprototype%-@@iterator
    if (!isCallable$a(IteratorPrototype$2[ITERATOR$7])) {
      defineBuiltIn$7(IteratorPrototype$2, ITERATOR$7, function () {
        return this;
      });
    }

    var iteratorsCore = {
      IteratorPrototype: IteratorPrototype$2,
      BUGGY_SAFARI_ITERATORS: BUGGY_SAFARI_ITERATORS$1
    };

    var defineProperty$4 = objectDefineProperty.f;
    var hasOwn$4 = hasOwnProperty_1;
    var wellKnownSymbol$h = wellKnownSymbol$n;

    var TO_STRING_TAG$1 = wellKnownSymbol$h('toStringTag');

    var setToStringTag$5 = function (target, TAG, STATIC) {
      if (target && !STATIC) target = target.prototype;
      if (target && !hasOwn$4(target, TO_STRING_TAG$1)) {
        defineProperty$4(target, TO_STRING_TAG$1, { configurable: true, value: TAG });
      }
    };

    var IteratorPrototype$1 = iteratorsCore.IteratorPrototype;
    var create$2 = objectCreate;
    var createPropertyDescriptor$2 = createPropertyDescriptor$5;
    var setToStringTag$4 = setToStringTag$5;
    var Iterators$4 = iterators;

    var returnThis$1 = function () { return this; };

    var iteratorCreateConstructor = function (IteratorConstructor, NAME, next, ENUMERABLE_NEXT) {
      var TO_STRING_TAG = NAME + ' Iterator';
      IteratorConstructor.prototype = create$2(IteratorPrototype$1, { next: createPropertyDescriptor$2(+!ENUMERABLE_NEXT, next) });
      setToStringTag$4(IteratorConstructor, TO_STRING_TAG, false);
      Iterators$4[TO_STRING_TAG] = returnThis$1;
      return IteratorConstructor;
    };

    var $$w = _export;
    var call$i = functionCall;
    var FunctionName$1 = functionName;
    var isCallable$9 = isCallable$p;
    var createIteratorConstructor = iteratorCreateConstructor;
    var getPrototypeOf$2 = objectGetPrototypeOf$1;
    var setPrototypeOf$4 = objectSetPrototypeOf;
    var setToStringTag$3 = setToStringTag$5;
    var createNonEnumerableProperty$7 = createNonEnumerableProperty$a;
    var defineBuiltIn$6 = defineBuiltIn$b;
    var wellKnownSymbol$g = wellKnownSymbol$n;
    var Iterators$3 = iterators;
    var IteratorsCore = iteratorsCore;

    var PROPER_FUNCTION_NAME$1 = FunctionName$1.PROPER;
    var CONFIGURABLE_FUNCTION_NAME$1 = FunctionName$1.CONFIGURABLE;
    var IteratorPrototype = IteratorsCore.IteratorPrototype;
    var BUGGY_SAFARI_ITERATORS = IteratorsCore.BUGGY_SAFARI_ITERATORS;
    var ITERATOR$6 = wellKnownSymbol$g('iterator');
    var KEYS = 'keys';
    var VALUES = 'values';
    var ENTRIES = 'entries';

    var returnThis = function () { return this; };

    var iteratorDefine = function (Iterable, NAME, IteratorConstructor, next, DEFAULT, IS_SET, FORCED) {
      createIteratorConstructor(IteratorConstructor, NAME, next);

      var getIterationMethod = function (KIND) {
        if (KIND === DEFAULT && defaultIterator) return defaultIterator;
        if (!BUGGY_SAFARI_ITERATORS && KIND && KIND in IterablePrototype) return IterablePrototype[KIND];

        switch (KIND) {
          case KEYS: return function keys() { return new IteratorConstructor(this, KIND); };
          case VALUES: return function values() { return new IteratorConstructor(this, KIND); };
          case ENTRIES: return function entries() { return new IteratorConstructor(this, KIND); };
        }

        return function () { return new IteratorConstructor(this); };
      };

      var TO_STRING_TAG = NAME + ' Iterator';
      var INCORRECT_VALUES_NAME = false;
      var IterablePrototype = Iterable.prototype;
      var nativeIterator = IterablePrototype[ITERATOR$6]
        || IterablePrototype['@@iterator']
        || DEFAULT && IterablePrototype[DEFAULT];
      var defaultIterator = !BUGGY_SAFARI_ITERATORS && nativeIterator || getIterationMethod(DEFAULT);
      var anyNativeIterator = NAME === 'Array' ? IterablePrototype.entries || nativeIterator : nativeIterator;
      var CurrentIteratorPrototype, methods, KEY;

      // fix native
      if (anyNativeIterator) {
        CurrentIteratorPrototype = getPrototypeOf$2(anyNativeIterator.call(new Iterable()));
        if (CurrentIteratorPrototype !== Object.prototype && CurrentIteratorPrototype.next) {
          if (getPrototypeOf$2(CurrentIteratorPrototype) !== IteratorPrototype) {
            if (setPrototypeOf$4) {
              setPrototypeOf$4(CurrentIteratorPrototype, IteratorPrototype);
            } else if (!isCallable$9(CurrentIteratorPrototype[ITERATOR$6])) {
              defineBuiltIn$6(CurrentIteratorPrototype, ITERATOR$6, returnThis);
            }
          }
          // Set @@toStringTag to native iterators
          setToStringTag$3(CurrentIteratorPrototype, TO_STRING_TAG, true);
        }
      }

      // fix Array.prototype.{ values, @@iterator }.name in V8 / FF
      if (PROPER_FUNCTION_NAME$1 && DEFAULT === VALUES && nativeIterator && nativeIterator.name !== VALUES) {
        if (CONFIGURABLE_FUNCTION_NAME$1) {
          createNonEnumerableProperty$7(IterablePrototype, 'name', VALUES);
        } else {
          INCORRECT_VALUES_NAME = true;
          defaultIterator = function values() { return call$i(nativeIterator, this); };
        }
      }

      // export additional methods
      if (DEFAULT) {
        methods = {
          values: getIterationMethod(VALUES),
          keys: IS_SET ? defaultIterator : getIterationMethod(KEYS),
          entries: getIterationMethod(ENTRIES)
        };
        if (FORCED) for (KEY in methods) {
          if (BUGGY_SAFARI_ITERATORS || INCORRECT_VALUES_NAME || !(KEY in IterablePrototype)) {
            defineBuiltIn$6(IterablePrototype, KEY, methods[KEY]);
          }
        } else $$w({ target: NAME, proto: true, forced: BUGGY_SAFARI_ITERATORS || INCORRECT_VALUES_NAME }, methods);
      }

      // define iterator
      if (IterablePrototype[ITERATOR$6] !== defaultIterator) {
        defineBuiltIn$6(IterablePrototype, ITERATOR$6, defaultIterator, { name: DEFAULT });
      }
      Iterators$3[NAME] = defaultIterator;

      return methods;
    };

    // `CreateIterResultObject` abstract operation
    // https://tc39.es/ecma262/#sec-createiterresultobject
    var createIterResultObject$2 = function (value, done) {
      return { value: value, done: done };
    };

    var toIndexedObject$5 = toIndexedObject$a;
    var addToUnscopables$3 = addToUnscopables$4;
    var Iterators$2 = iterators;
    var InternalStateModule$5 = internalState;
    var defineProperty$3 = objectDefineProperty.f;
    var defineIterator$1 = iteratorDefine;
    var createIterResultObject$1 = createIterResultObject$2;
    var DESCRIPTORS$c = descriptors;

    var ARRAY_ITERATOR = 'Array Iterator';
    var setInternalState$4 = InternalStateModule$5.set;
    var getInternalState$4 = InternalStateModule$5.getterFor(ARRAY_ITERATOR);

    // `Array.prototype.entries` method
    // https://tc39.es/ecma262/#sec-array.prototype.entries
    // `Array.prototype.keys` method
    // https://tc39.es/ecma262/#sec-array.prototype.keys
    // `Array.prototype.values` method
    // https://tc39.es/ecma262/#sec-array.prototype.values
    // `Array.prototype[@@iterator]` method
    // https://tc39.es/ecma262/#sec-array.prototype-@@iterator
    // `CreateArrayIterator` internal method
    // https://tc39.es/ecma262/#sec-createarrayiterator
    var es_array_iterator = defineIterator$1(Array, 'Array', function (iterated, kind) {
      setInternalState$4(this, {
        type: ARRAY_ITERATOR,
        target: toIndexedObject$5(iterated), // target
        index: 0,                          // next index
        kind: kind                         // kind
      });
    // `%ArrayIteratorPrototype%.next` method
    // https://tc39.es/ecma262/#sec-%arrayiteratorprototype%.next
    }, function () {
      var state = getInternalState$4(this);
      var target = state.target;
      var index = state.index++;
      if (!target || index >= target.length) {
        state.target = null;
        return createIterResultObject$1(undefined, true);
      }
      switch (state.kind) {
        case 'keys': return createIterResultObject$1(index, false);
        case 'values': return createIterResultObject$1(target[index], false);
      } return createIterResultObject$1([index, target[index]], false);
    }, 'values');

    // argumentsList[@@iterator] is %ArrayProto_values%
    // https://tc39.es/ecma262/#sec-createunmappedargumentsobject
    // https://tc39.es/ecma262/#sec-createmappedargumentsobject
    var values = Iterators$2.Arguments = Iterators$2.Array;

    // https://tc39.es/ecma262/#sec-array.prototype-@@unscopables
    addToUnscopables$3('keys');
    addToUnscopables$3('values');
    addToUnscopables$3('entries');

    // V8 ~ Chrome 45- bug
    if (DESCRIPTORS$c && values.name !== 'values') try {
      defineProperty$3(values, 'name', { value: 'values' });
    } catch (error) { /* empty */ }

    var classofRaw = classofRaw$2;
    var uncurryThis$p = functionUncurryThis;

    var functionUncurryThisClause = function (fn) {
      // Nashorn bug:
      //   https://github.com/zloirock/core-js/issues/1128
      //   https://github.com/zloirock/core-js/issues/1130
      if (classofRaw(fn) === 'Function') return uncurryThis$p(fn);
    };

    // eslint-disable-next-line es/no-typed-arrays -- safe
    var arrayBufferBasicDetection = typeof ArrayBuffer != 'undefined' && typeof DataView != 'undefined';

    var makeBuiltIn = makeBuiltIn$3.exports;
    var defineProperty$2 = objectDefineProperty;

    var defineBuiltInAccessor$6 = function (target, name, descriptor) {
      if (descriptor.get) makeBuiltIn(descriptor.get, name, { getter: true });
      if (descriptor.set) makeBuiltIn(descriptor.set, name, { setter: true });
      return defineProperty$2.f(target, name, descriptor);
    };

    var defineBuiltIn$5 = defineBuiltIn$b;

    var defineBuiltIns$1 = function (target, src, options) {
      for (var key in src) defineBuiltIn$5(target, key, src[key], options);
      return target;
    };

    var isPrototypeOf$4 = objectIsPrototypeOf;

    var $TypeError$d = TypeError;

    var anInstance$3 = function (it, Prototype) {
      if (isPrototypeOf$4(Prototype, it)) return it;
      throw new $TypeError$d('Incorrect invocation');
    };

    var toIntegerOrInfinity$6 = toIntegerOrInfinity$9;
    var toLength$7 = toLength$9;

    var $RangeError$2 = RangeError;

    // `ToIndex` abstract operation
    // https://tc39.es/ecma262/#sec-toindex
    var toIndex$2 = function (it) {
      if (it === undefined) return 0;
      var number = toIntegerOrInfinity$6(it);
      var length = toLength$7(number);
      if (number !== length) throw new $RangeError$2('Wrong length or index');
      return length;
    };

    // `Math.sign` method implementation
    // https://tc39.es/ecma262/#sec-math.sign
    // eslint-disable-next-line es/no-math-sign -- safe
    var mathSign = Math.sign || function sign(x) {
      var n = +x;
      // eslint-disable-next-line no-self-compare -- NaN check
      return n === 0 || n !== n ? n : n < 0 ? -1 : 1;
    };

    var sign = mathSign;

    var abs$1 = Math.abs;

    var EPSILON = 2.220446049250313e-16; // Number.EPSILON
    var INVERSE_EPSILON = 1 / EPSILON;

    var roundTiesToEven = function (n) {
      return n + INVERSE_EPSILON - INVERSE_EPSILON;
    };

    var mathFloatRound = function (x, FLOAT_EPSILON, FLOAT_MAX_VALUE, FLOAT_MIN_VALUE) {
      var n = +x;
      var absolute = abs$1(n);
      var s = sign(n);
      if (absolute < FLOAT_MIN_VALUE) return s * roundTiesToEven(absolute / FLOAT_MIN_VALUE / FLOAT_EPSILON) * FLOAT_MIN_VALUE * FLOAT_EPSILON;
      var a = (1 + FLOAT_EPSILON / EPSILON) * absolute;
      var result = a - (a - absolute);
      // eslint-disable-next-line no-self-compare -- NaN check
      if (result > FLOAT_MAX_VALUE || result !== result) return s * Infinity;
      return s * result;
    };

    var floatRound = mathFloatRound;

    var FLOAT32_EPSILON = 1.1920928955078125e-7; // 2 ** -23;
    var FLOAT32_MAX_VALUE = 3.4028234663852886e+38; // 2 ** 128 - 2 ** 104
    var FLOAT32_MIN_VALUE = 1.1754943508222875e-38; // 2 ** -126;

    // `Math.fround` method implementation
    // https://tc39.es/ecma262/#sec-math.fround
    // eslint-disable-next-line es/no-math-fround -- safe
    var mathFround = Math.fround || function fround(x) {
      return floatRound(x, FLOAT32_EPSILON, FLOAT32_MAX_VALUE, FLOAT32_MIN_VALUE);
    };

    // IEEE754 conversions based on https://github.com/feross/ieee754
    var $Array$3 = Array;
    var abs = Math.abs;
    var pow = Math.pow;
    var floor$3 = Math.floor;
    var log = Math.log;
    var LN2 = Math.LN2;

    var pack = function (number, mantissaLength, bytes) {
      var buffer = $Array$3(bytes);
      var exponentLength = bytes * 8 - mantissaLength - 1;
      var eMax = (1 << exponentLength) - 1;
      var eBias = eMax >> 1;
      var rt = mantissaLength === 23 ? pow(2, -24) - pow(2, -77) : 0;
      var sign = number < 0 || number === 0 && 1 / number < 0 ? 1 : 0;
      var index = 0;
      var exponent, mantissa, c;
      number = abs(number);
      // eslint-disable-next-line no-self-compare -- NaN check
      if (number !== number || number === Infinity) {
        // eslint-disable-next-line no-self-compare -- NaN check
        mantissa = number !== number ? 1 : 0;
        exponent = eMax;
      } else {
        exponent = floor$3(log(number) / LN2);
        c = pow(2, -exponent);
        if (number * c < 1) {
          exponent--;
          c *= 2;
        }
        if (exponent + eBias >= 1) {
          number += rt / c;
        } else {
          number += rt * pow(2, 1 - eBias);
        }
        if (number * c >= 2) {
          exponent++;
          c /= 2;
        }
        if (exponent + eBias >= eMax) {
          mantissa = 0;
          exponent = eMax;
        } else if (exponent + eBias >= 1) {
          mantissa = (number * c - 1) * pow(2, mantissaLength);
          exponent += eBias;
        } else {
          mantissa = number * pow(2, eBias - 1) * pow(2, mantissaLength);
          exponent = 0;
        }
      }
      while (mantissaLength >= 8) {
        buffer[index++] = mantissa & 255;
        mantissa /= 256;
        mantissaLength -= 8;
      }
      exponent = exponent << mantissaLength | mantissa;
      exponentLength += mantissaLength;
      while (exponentLength > 0) {
        buffer[index++] = exponent & 255;
        exponent /= 256;
        exponentLength -= 8;
      }
      buffer[index - 1] |= sign * 128;
      return buffer;
    };

    var unpack = function (buffer, mantissaLength) {
      var bytes = buffer.length;
      var exponentLength = bytes * 8 - mantissaLength - 1;
      var eMax = (1 << exponentLength) - 1;
      var eBias = eMax >> 1;
      var nBits = exponentLength - 7;
      var index = bytes - 1;
      var sign = buffer[index--];
      var exponent = sign & 127;
      var mantissa;
      sign >>= 7;
      while (nBits > 0) {
        exponent = exponent * 256 + buffer[index--];
        nBits -= 8;
      }
      mantissa = exponent & (1 << -nBits) - 1;
      exponent >>= -nBits;
      nBits += mantissaLength;
      while (nBits > 0) {
        mantissa = mantissa * 256 + buffer[index--];
        nBits -= 8;
      }
      if (exponent === 0) {
        exponent = 1 - eBias;
      } else if (exponent === eMax) {
        return mantissa ? NaN : sign ? -Infinity : Infinity;
      } else {
        mantissa += pow(2, mantissaLength);
        exponent -= eBias;
      } return (sign ? -1 : 1) * mantissa * pow(2, exponent - mantissaLength);
    };

    var ieee754 = {
      pack: pack,
      unpack: unpack
    };

    var toObject$9 = toObject$c;
    var toAbsoluteIndex$5 = toAbsoluteIndex$7;
    var lengthOfArrayLike$c = lengthOfArrayLike$e;

    // `Array.prototype.fill` method implementation
    // https://tc39.es/ecma262/#sec-array.prototype.fill
    var arrayFill$1 = function fill(value /* , start = 0, end = @length */) {
      var O = toObject$9(this);
      var length = lengthOfArrayLike$c(O);
      var argumentsLength = arguments.length;
      var index = toAbsoluteIndex$5(argumentsLength > 1 ? arguments[1] : undefined, length);
      var end = argumentsLength > 2 ? arguments[2] : undefined;
      var endPos = end === undefined ? length : toAbsoluteIndex$5(end, length);
      while (endPos > index) O[index++] = value;
      return O;
    };

    var uncurryThis$o = functionUncurryThis;

    var arraySlice$6 = uncurryThis$o([].slice);

    var globalThis$l = globalThis_1;
    var uncurryThis$n = functionUncurryThis;
    var DESCRIPTORS$b = descriptors;
    var NATIVE_ARRAY_BUFFER$1 = arrayBufferBasicDetection;
    var FunctionName = functionName;
    var createNonEnumerableProperty$6 = createNonEnumerableProperty$a;
    var defineBuiltInAccessor$5 = defineBuiltInAccessor$6;
    var defineBuiltIns = defineBuiltIns$1;
    var fails$m = fails$C;
    var anInstance$2 = anInstance$3;
    var toIntegerOrInfinity$5 = toIntegerOrInfinity$9;
    var toLength$6 = toLength$9;
    var toIndex$1 = toIndex$2;
    var fround = mathFround;
    var IEEE754 = ieee754;
    var getPrototypeOf$1 = objectGetPrototypeOf$1;
    var setPrototypeOf$3 = objectSetPrototypeOf;
    var arrayFill = arrayFill$1;
    var arraySlice$5 = arraySlice$6;
    var inheritIfRequired$2 = inheritIfRequired$4;
    var copyConstructorProperties = copyConstructorProperties$3;
    var setToStringTag$2 = setToStringTag$5;
    var InternalStateModule$4 = internalState;

    var PROPER_FUNCTION_NAME = FunctionName.PROPER;
    var CONFIGURABLE_FUNCTION_NAME = FunctionName.CONFIGURABLE;
    var ARRAY_BUFFER$1 = 'ArrayBuffer';
    var DATA_VIEW = 'DataView';
    var PROTOTYPE = 'prototype';
    var WRONG_LENGTH$1 = 'Wrong length';
    var WRONG_INDEX = 'Wrong index';
    var getInternalArrayBufferState = InternalStateModule$4.getterFor(ARRAY_BUFFER$1);
    var getInternalDataViewState = InternalStateModule$4.getterFor(DATA_VIEW);
    var setInternalState$3 = InternalStateModule$4.set;
    var NativeArrayBuffer$1 = globalThis$l[ARRAY_BUFFER$1];
    var $ArrayBuffer = NativeArrayBuffer$1;
    var ArrayBufferPrototype$1 = $ArrayBuffer && $ArrayBuffer[PROTOTYPE];
    var $DataView = globalThis$l[DATA_VIEW];
    var DataViewPrototype$1 = $DataView && $DataView[PROTOTYPE];
    var ObjectPrototype$1 = Object.prototype;
    var Array$1 = globalThis$l.Array;
    var RangeError$3 = globalThis$l.RangeError;
    var fill = uncurryThis$n(arrayFill);
    var reverse = uncurryThis$n([].reverse);

    var packIEEE754 = IEEE754.pack;
    var unpackIEEE754 = IEEE754.unpack;

    var packInt8 = function (number) {
      return [number & 0xFF];
    };

    var packInt16 = function (number) {
      return [number & 0xFF, number >> 8 & 0xFF];
    };

    var packInt32 = function (number) {
      return [number & 0xFF, number >> 8 & 0xFF, number >> 16 & 0xFF, number >> 24 & 0xFF];
    };

    var unpackInt32 = function (buffer) {
      return buffer[3] << 24 | buffer[2] << 16 | buffer[1] << 8 | buffer[0];
    };

    var packFloat32 = function (number) {
      return packIEEE754(fround(number), 23, 4);
    };

    var packFloat64 = function (number) {
      return packIEEE754(number, 52, 8);
    };

    var addGetter$1 = function (Constructor, key, getInternalState) {
      defineBuiltInAccessor$5(Constructor[PROTOTYPE], key, {
        configurable: true,
        get: function () {
          return getInternalState(this)[key];
        }
      });
    };

    var get = function (view, count, index, isLittleEndian) {
      var store = getInternalDataViewState(view);
      var intIndex = toIndex$1(index);
      var boolIsLittleEndian = !!isLittleEndian;
      if (intIndex + count > store.byteLength) throw new RangeError$3(WRONG_INDEX);
      var bytes = store.bytes;
      var start = intIndex + store.byteOffset;
      var pack = arraySlice$5(bytes, start, start + count);
      return boolIsLittleEndian ? pack : reverse(pack);
    };

    var set$1 = function (view, count, index, conversion, value, isLittleEndian) {
      var store = getInternalDataViewState(view);
      var intIndex = toIndex$1(index);
      var pack = conversion(+value);
      var boolIsLittleEndian = !!isLittleEndian;
      if (intIndex + count > store.byteLength) throw new RangeError$3(WRONG_INDEX);
      var bytes = store.bytes;
      var start = intIndex + store.byteOffset;
      for (var i = 0; i < count; i++) bytes[start + i] = pack[boolIsLittleEndian ? i : count - i - 1];
    };

    if (!NATIVE_ARRAY_BUFFER$1) {
      $ArrayBuffer = function ArrayBuffer(length) {
        anInstance$2(this, ArrayBufferPrototype$1);
        var byteLength = toIndex$1(length);
        setInternalState$3(this, {
          type: ARRAY_BUFFER$1,
          bytes: fill(Array$1(byteLength), 0),
          byteLength: byteLength
        });
        if (!DESCRIPTORS$b) {
          this.byteLength = byteLength;
          this.detached = false;
        }
      };

      ArrayBufferPrototype$1 = $ArrayBuffer[PROTOTYPE];

      $DataView = function DataView(buffer, byteOffset, byteLength) {
        anInstance$2(this, DataViewPrototype$1);
        anInstance$2(buffer, ArrayBufferPrototype$1);
        var bufferState = getInternalArrayBufferState(buffer);
        var bufferLength = bufferState.byteLength;
        var offset = toIntegerOrInfinity$5(byteOffset);
        if (offset < 0 || offset > bufferLength) throw new RangeError$3('Wrong offset');
        byteLength = byteLength === undefined ? bufferLength - offset : toLength$6(byteLength);
        if (offset + byteLength > bufferLength) throw new RangeError$3(WRONG_LENGTH$1);
        setInternalState$3(this, {
          type: DATA_VIEW,
          buffer: buffer,
          byteLength: byteLength,
          byteOffset: offset,
          bytes: bufferState.bytes
        });
        if (!DESCRIPTORS$b) {
          this.buffer = buffer;
          this.byteLength = byteLength;
          this.byteOffset = offset;
        }
      };

      DataViewPrototype$1 = $DataView[PROTOTYPE];

      if (DESCRIPTORS$b) {
        addGetter$1($ArrayBuffer, 'byteLength', getInternalArrayBufferState);
        addGetter$1($DataView, 'buffer', getInternalDataViewState);
        addGetter$1($DataView, 'byteLength', getInternalDataViewState);
        addGetter$1($DataView, 'byteOffset', getInternalDataViewState);
      }

      defineBuiltIns(DataViewPrototype$1, {
        getInt8: function getInt8(byteOffset) {
          return get(this, 1, byteOffset)[0] << 24 >> 24;
        },
        getUint8: function getUint8(byteOffset) {
          return get(this, 1, byteOffset)[0];
        },
        getInt16: function getInt16(byteOffset /* , littleEndian */) {
          var bytes = get(this, 2, byteOffset, arguments.length > 1 ? arguments[1] : false);
          return (bytes[1] << 8 | bytes[0]) << 16 >> 16;
        },
        getUint16: function getUint16(byteOffset /* , littleEndian */) {
          var bytes = get(this, 2, byteOffset, arguments.length > 1 ? arguments[1] : false);
          return bytes[1] << 8 | bytes[0];
        },
        getInt32: function getInt32(byteOffset /* , littleEndian */) {
          return unpackInt32(get(this, 4, byteOffset, arguments.length > 1 ? arguments[1] : false));
        },
        getUint32: function getUint32(byteOffset /* , littleEndian */) {
          return unpackInt32(get(this, 4, byteOffset, arguments.length > 1 ? arguments[1] : false)) >>> 0;
        },
        getFloat32: function getFloat32(byteOffset /* , littleEndian */) {
          return unpackIEEE754(get(this, 4, byteOffset, arguments.length > 1 ? arguments[1] : false), 23);
        },
        getFloat64: function getFloat64(byteOffset /* , littleEndian */) {
          return unpackIEEE754(get(this, 8, byteOffset, arguments.length > 1 ? arguments[1] : false), 52);
        },
        setInt8: function setInt8(byteOffset, value) {
          set$1(this, 1, byteOffset, packInt8, value);
        },
        setUint8: function setUint8(byteOffset, value) {
          set$1(this, 1, byteOffset, packInt8, value);
        },
        setInt16: function setInt16(byteOffset, value /* , littleEndian */) {
          set$1(this, 2, byteOffset, packInt16, value, arguments.length > 2 ? arguments[2] : false);
        },
        setUint16: function setUint16(byteOffset, value /* , littleEndian */) {
          set$1(this, 2, byteOffset, packInt16, value, arguments.length > 2 ? arguments[2] : false);
        },
        setInt32: function setInt32(byteOffset, value /* , littleEndian */) {
          set$1(this, 4, byteOffset, packInt32, value, arguments.length > 2 ? arguments[2] : false);
        },
        setUint32: function setUint32(byteOffset, value /* , littleEndian */) {
          set$1(this, 4, byteOffset, packInt32, value, arguments.length > 2 ? arguments[2] : false);
        },
        setFloat32: function setFloat32(byteOffset, value /* , littleEndian */) {
          set$1(this, 4, byteOffset, packFloat32, value, arguments.length > 2 ? arguments[2] : false);
        },
        setFloat64: function setFloat64(byteOffset, value /* , littleEndian */) {
          set$1(this, 8, byteOffset, packFloat64, value, arguments.length > 2 ? arguments[2] : false);
        }
      });
    } else {
      var INCORRECT_ARRAY_BUFFER_NAME = PROPER_FUNCTION_NAME && NativeArrayBuffer$1.name !== ARRAY_BUFFER$1;
      /* eslint-disable no-new, sonar/inconsistent-function-call -- required for testing */
      if (!fails$m(function () {
        NativeArrayBuffer$1(1);
      }) || !fails$m(function () {
        new NativeArrayBuffer$1(-1);
      }) || fails$m(function () {
        new NativeArrayBuffer$1();
        new NativeArrayBuffer$1(1.5);
        new NativeArrayBuffer$1(NaN);
        return NativeArrayBuffer$1.length !== 1 || INCORRECT_ARRAY_BUFFER_NAME && !CONFIGURABLE_FUNCTION_NAME;
      })) {
        /* eslint-enable no-new, sonar/inconsistent-function-call -- required for testing */
        $ArrayBuffer = function ArrayBuffer(length) {
          anInstance$2(this, ArrayBufferPrototype$1);
          return inheritIfRequired$2(new NativeArrayBuffer$1(toIndex$1(length)), this, $ArrayBuffer);
        };

        $ArrayBuffer[PROTOTYPE] = ArrayBufferPrototype$1;

        ArrayBufferPrototype$1.constructor = $ArrayBuffer;

        copyConstructorProperties($ArrayBuffer, NativeArrayBuffer$1);
      } else if (INCORRECT_ARRAY_BUFFER_NAME && CONFIGURABLE_FUNCTION_NAME) {
        createNonEnumerableProperty$6(NativeArrayBuffer$1, 'name', ARRAY_BUFFER$1);
      }

      // WebKit bug - the same parent prototype for typed arrays and data view
      if (setPrototypeOf$3 && getPrototypeOf$1(DataViewPrototype$1) !== ObjectPrototype$1) {
        setPrototypeOf$3(DataViewPrototype$1, ObjectPrototype$1);
      }

      // iOS Safari 7.x bug
      var testView = new $DataView(new $ArrayBuffer(2));
      var $setInt8 = uncurryThis$n(DataViewPrototype$1.setInt8);
      testView.setInt8(0, 2147483648);
      testView.setInt8(1, 2147483649);
      if (testView.getInt8(0) || !testView.getInt8(1)) defineBuiltIns(DataViewPrototype$1, {
        setInt8: function setInt8(byteOffset, value) {
          $setInt8(this, byteOffset, value << 24 >> 24);
        },
        setUint8: function setUint8(byteOffset, value) {
          $setInt8(this, byteOffset, value << 24 >> 24);
        }
      }, { unsafe: true });
    }

    setToStringTag$2($ArrayBuffer, ARRAY_BUFFER$1);
    setToStringTag$2($DataView, DATA_VIEW);

    var arrayBuffer = {
      ArrayBuffer: $ArrayBuffer,
      DataView: $DataView
    };

    var uncurryThis$m = functionUncurryThis;
    var fails$l = fails$C;
    var isCallable$8 = isCallable$p;
    var classof$b = classof$f;
    var getBuiltIn$4 = getBuiltIn$8;
    var inspectSource$1 = inspectSource$3;

    var noop = function () { /* empty */ };
    var construct = getBuiltIn$4('Reflect', 'construct');
    var constructorRegExp = /^\s*(?:class|function)\b/;
    var exec$3 = uncurryThis$m(constructorRegExp.exec);
    var INCORRECT_TO_STRING = !constructorRegExp.test(noop);

    var isConstructorModern = function isConstructor(argument) {
      if (!isCallable$8(argument)) return false;
      try {
        construct(noop, [], argument);
        return true;
      } catch (error) {
        return false;
      }
    };

    var isConstructorLegacy = function isConstructor(argument) {
      if (!isCallable$8(argument)) return false;
      switch (classof$b(argument)) {
        case 'AsyncFunction':
        case 'GeneratorFunction':
        case 'AsyncGeneratorFunction': return false;
      }
      try {
        // we can't check .prototype since constructors produced by .bind haven't it
        // `Function#toString` throws on some built-it function in some legacy engines
        // (for example, `DOMQuad` and similar in FF41-)
        return INCORRECT_TO_STRING || !!exec$3(constructorRegExp, inspectSource$1(argument));
      } catch (error) {
        return true;
      }
    };

    isConstructorLegacy.sham = true;

    // `IsConstructor` abstract operation
    // https://tc39.es/ecma262/#sec-isconstructor
    var isConstructor$4 = !construct || fails$l(function () {
      var called;
      return isConstructorModern(isConstructorModern.call)
        || !isConstructorModern(Object)
        || !isConstructorModern(function () { called = true; })
        || called;
    }) ? isConstructorLegacy : isConstructorModern;

    var isConstructor$3 = isConstructor$4;
    var tryToString$4 = tryToString$6;

    var $TypeError$c = TypeError;

    // `Assert: IsConstructor(argument) is true`
    var aConstructor$2 = function (argument) {
      if (isConstructor$3(argument)) return argument;
      throw new $TypeError$c(tryToString$4(argument) + ' is not a constructor');
    };

    var anObject$8 = anObject$g;
    var aConstructor$1 = aConstructor$2;
    var isNullOrUndefined$2 = isNullOrUndefined$5;
    var wellKnownSymbol$f = wellKnownSymbol$n;

    var SPECIES$6 = wellKnownSymbol$f('species');

    // `SpeciesConstructor` abstract operation
    // https://tc39.es/ecma262/#sec-speciesconstructor
    var speciesConstructor$3 = function (O, defaultConstructor) {
      var C = anObject$8(O).constructor;
      var S;
      return C === undefined || isNullOrUndefined$2(S = anObject$8(C)[SPECIES$6]) ? defaultConstructor : aConstructor$1(S);
    };

    var $$v = _export;
    var uncurryThis$l = functionUncurryThisClause;
    var fails$k = fails$C;
    var ArrayBufferModule$1 = arrayBuffer;
    var anObject$7 = anObject$g;
    var toAbsoluteIndex$4 = toAbsoluteIndex$7;
    var toLength$5 = toLength$9;
    var speciesConstructor$2 = speciesConstructor$3;

    var ArrayBuffer$4 = ArrayBufferModule$1.ArrayBuffer;
    var DataView$2 = ArrayBufferModule$1.DataView;
    var DataViewPrototype = DataView$2.prototype;
    var nativeArrayBufferSlice = uncurryThis$l(ArrayBuffer$4.prototype.slice);
    var getUint8 = uncurryThis$l(DataViewPrototype.getUint8);
    var setUint8 = uncurryThis$l(DataViewPrototype.setUint8);

    var INCORRECT_SLICE = fails$k(function () {
      return !new ArrayBuffer$4(2).slice(1, undefined).byteLength;
    });

    // `ArrayBuffer.prototype.slice` method
    // https://tc39.es/ecma262/#sec-arraybuffer.prototype.slice
    $$v({ target: 'ArrayBuffer', proto: true, unsafe: true, forced: INCORRECT_SLICE }, {
      slice: function slice(start, end) {
        if (nativeArrayBufferSlice && end === undefined) {
          return nativeArrayBufferSlice(anObject$7(this), start); // FF fix
        }
        var length = anObject$7(this).byteLength;
        var first = toAbsoluteIndex$4(start, length);
        var fin = toAbsoluteIndex$4(end === undefined ? length : end, length);
        var result = new (speciesConstructor$2(this, ArrayBuffer$4))(toLength$5(fin - first));
        var viewSource = new DataView$2(this);
        var viewTarget = new DataView$2(result);
        var index = 0;
        while (first < fin) {
          setUint8(viewTarget, index++, getUint8(viewSource, first++));
        } return result;
      }
    });

    var typedArrayConstructor = {exports: {}};

    var wellKnownSymbol$e = wellKnownSymbol$n;

    var ITERATOR$5 = wellKnownSymbol$e('iterator');
    var SAFE_CLOSING = false;

    try {
      var called = 0;
      var iteratorWithReturn = {
        next: function () {
          return { done: !!called++ };
        },
        'return': function () {
          SAFE_CLOSING = true;
        }
      };
      iteratorWithReturn[ITERATOR$5] = function () {
        return this;
      };
      // eslint-disable-next-line es/no-array-from, no-throw-literal -- required for testing
      Array.from(iteratorWithReturn, function () { throw 2; });
    } catch (error) { /* empty */ }

    var checkCorrectnessOfIteration$3 = function (exec, SKIP_CLOSING) {
      try {
        if (!SKIP_CLOSING && !SAFE_CLOSING) return false;
      } catch (error) { return false; } // workaround of old WebKit + `eval` bug
      var ITERATION_SUPPORT = false;
      try {
        var object = {};
        object[ITERATOR$5] = function () {
          return {
            next: function () {
              return { done: ITERATION_SUPPORT = true };
            }
          };
        };
        exec(object);
      } catch (error) { /* empty */ }
      return ITERATION_SUPPORT;
    };

    var NATIVE_ARRAY_BUFFER = arrayBufferBasicDetection;
    var DESCRIPTORS$a = descriptors;
    var globalThis$k = globalThis_1;
    var isCallable$7 = isCallable$p;
    var isObject$7 = isObject$h;
    var hasOwn$3 = hasOwnProperty_1;
    var classof$a = classof$f;
    var tryToString$3 = tryToString$6;
    var createNonEnumerableProperty$5 = createNonEnumerableProperty$a;
    var defineBuiltIn$4 = defineBuiltIn$b;
    var defineBuiltInAccessor$4 = defineBuiltInAccessor$6;
    var isPrototypeOf$3 = objectIsPrototypeOf;
    var getPrototypeOf = objectGetPrototypeOf$1;
    var setPrototypeOf$2 = objectSetPrototypeOf;
    var wellKnownSymbol$d = wellKnownSymbol$n;
    var uid = uid$3;
    var InternalStateModule$3 = internalState;

    var enforceInternalState$2 = InternalStateModule$3.enforce;
    var getInternalState$3 = InternalStateModule$3.get;
    var Int8Array$4 = globalThis$k.Int8Array;
    var Int8ArrayPrototype$1 = Int8Array$4 && Int8Array$4.prototype;
    var Uint8ClampedArray$1 = globalThis$k.Uint8ClampedArray;
    var Uint8ClampedArrayPrototype = Uint8ClampedArray$1 && Uint8ClampedArray$1.prototype;
    var TypedArray$1 = Int8Array$4 && getPrototypeOf(Int8Array$4);
    var TypedArrayPrototype$2 = Int8ArrayPrototype$1 && getPrototypeOf(Int8ArrayPrototype$1);
    var ObjectPrototype = Object.prototype;
    var TypeError$2 = globalThis$k.TypeError;

    var TO_STRING_TAG = wellKnownSymbol$d('toStringTag');
    var TYPED_ARRAY_TAG$1 = uid('TYPED_ARRAY_TAG');
    var TYPED_ARRAY_CONSTRUCTOR = 'TypedArrayConstructor';
    // Fixing native typed arrays in Opera Presto crashes the browser, see #595
    var NATIVE_ARRAY_BUFFER_VIEWS$3 = NATIVE_ARRAY_BUFFER && !!setPrototypeOf$2 && classof$a(globalThis$k.opera) !== 'Opera';
    var TYPED_ARRAY_TAG_REQUIRED = false;
    var NAME$1, Constructor, Prototype;

    var TypedArrayConstructorsList = {
      Int8Array: 1,
      Uint8Array: 1,
      Uint8ClampedArray: 1,
      Int16Array: 2,
      Uint16Array: 2,
      Int32Array: 4,
      Uint32Array: 4,
      Float32Array: 4,
      Float64Array: 8
    };

    var BigIntArrayConstructorsList = {
      BigInt64Array: 8,
      BigUint64Array: 8
    };

    var isView = function isView(it) {
      if (!isObject$7(it)) return false;
      var klass = classof$a(it);
      return klass === 'DataView'
        || hasOwn$3(TypedArrayConstructorsList, klass)
        || hasOwn$3(BigIntArrayConstructorsList, klass);
    };

    var getTypedArrayConstructor$1 = function (it) {
      var proto = getPrototypeOf(it);
      if (!isObject$7(proto)) return;
      var state = getInternalState$3(proto);
      return (state && hasOwn$3(state, TYPED_ARRAY_CONSTRUCTOR)) ? state[TYPED_ARRAY_CONSTRUCTOR] : getTypedArrayConstructor$1(proto);
    };

    var isTypedArray$1 = function (it) {
      if (!isObject$7(it)) return false;
      var klass = classof$a(it);
      return hasOwn$3(TypedArrayConstructorsList, klass)
        || hasOwn$3(BigIntArrayConstructorsList, klass);
    };

    var aTypedArray$n = function (it) {
      if (isTypedArray$1(it)) return it;
      throw new TypeError$2('Target is not a typed array');
    };

    var aTypedArrayConstructor$2 = function (C) {
      if (isCallable$7(C) && (!setPrototypeOf$2 || isPrototypeOf$3(TypedArray$1, C))) return C;
      throw new TypeError$2(tryToString$3(C) + ' is not a typed array constructor');
    };

    var exportTypedArrayMethod$o = function (KEY, property, forced, options) {
      if (!DESCRIPTORS$a) return;
      if (forced) for (var ARRAY in TypedArrayConstructorsList) {
        var TypedArrayConstructor = globalThis$k[ARRAY];
        if (TypedArrayConstructor && hasOwn$3(TypedArrayConstructor.prototype, KEY)) try {
          delete TypedArrayConstructor.prototype[KEY];
        } catch (error) {
          // old WebKit bug - some methods are non-configurable
          try {
            TypedArrayConstructor.prototype[KEY] = property;
          } catch (error2) { /* empty */ }
        }
      }
      if (!TypedArrayPrototype$2[KEY] || forced) {
        defineBuiltIn$4(TypedArrayPrototype$2, KEY, forced ? property
          : NATIVE_ARRAY_BUFFER_VIEWS$3 && Int8ArrayPrototype$1[KEY] || property, options);
      }
    };

    var exportTypedArrayStaticMethod = function (KEY, property, forced) {
      var ARRAY, TypedArrayConstructor;
      if (!DESCRIPTORS$a) return;
      if (setPrototypeOf$2) {
        if (forced) for (ARRAY in TypedArrayConstructorsList) {
          TypedArrayConstructor = globalThis$k[ARRAY];
          if (TypedArrayConstructor && hasOwn$3(TypedArrayConstructor, KEY)) try {
            delete TypedArrayConstructor[KEY];
          } catch (error) { /* empty */ }
        }
        if (!TypedArray$1[KEY] || forced) {
          // V8 ~ Chrome 49-50 `%TypedArray%` methods are non-writable non-configurable
          try {
            return defineBuiltIn$4(TypedArray$1, KEY, forced ? property : NATIVE_ARRAY_BUFFER_VIEWS$3 && TypedArray$1[KEY] || property);
          } catch (error) { /* empty */ }
        } else return;
      }
      for (ARRAY in TypedArrayConstructorsList) {
        TypedArrayConstructor = globalThis$k[ARRAY];
        if (TypedArrayConstructor && (!TypedArrayConstructor[KEY] || forced)) {
          defineBuiltIn$4(TypedArrayConstructor, KEY, property);
        }
      }
    };

    for (NAME$1 in TypedArrayConstructorsList) {
      Constructor = globalThis$k[NAME$1];
      Prototype = Constructor && Constructor.prototype;
      if (Prototype) enforceInternalState$2(Prototype)[TYPED_ARRAY_CONSTRUCTOR] = Constructor;
      else NATIVE_ARRAY_BUFFER_VIEWS$3 = false;
    }

    for (NAME$1 in BigIntArrayConstructorsList) {
      Constructor = globalThis$k[NAME$1];
      Prototype = Constructor && Constructor.prototype;
      if (Prototype) enforceInternalState$2(Prototype)[TYPED_ARRAY_CONSTRUCTOR] = Constructor;
    }

    // WebKit bug - typed arrays constructors prototype is Object.prototype
    if (!NATIVE_ARRAY_BUFFER_VIEWS$3 || !isCallable$7(TypedArray$1) || TypedArray$1 === Function.prototype) {
      // eslint-disable-next-line no-shadow -- safe
      TypedArray$1 = function TypedArray() {
        throw new TypeError$2('Incorrect invocation');
      };
      if (NATIVE_ARRAY_BUFFER_VIEWS$3) for (NAME$1 in TypedArrayConstructorsList) {
        if (globalThis$k[NAME$1]) setPrototypeOf$2(globalThis$k[NAME$1], TypedArray$1);
      }
    }

    if (!NATIVE_ARRAY_BUFFER_VIEWS$3 || !TypedArrayPrototype$2 || TypedArrayPrototype$2 === ObjectPrototype) {
      TypedArrayPrototype$2 = TypedArray$1.prototype;
      if (NATIVE_ARRAY_BUFFER_VIEWS$3) for (NAME$1 in TypedArrayConstructorsList) {
        if (globalThis$k[NAME$1]) setPrototypeOf$2(globalThis$k[NAME$1].prototype, TypedArrayPrototype$2);
      }
    }

    // WebKit bug - one more object in Uint8ClampedArray prototype chain
    if (NATIVE_ARRAY_BUFFER_VIEWS$3 && getPrototypeOf(Uint8ClampedArrayPrototype) !== TypedArrayPrototype$2) {
      setPrototypeOf$2(Uint8ClampedArrayPrototype, TypedArrayPrototype$2);
    }

    if (DESCRIPTORS$a && !hasOwn$3(TypedArrayPrototype$2, TO_STRING_TAG)) {
      TYPED_ARRAY_TAG_REQUIRED = true;
      defineBuiltInAccessor$4(TypedArrayPrototype$2, TO_STRING_TAG, {
        configurable: true,
        get: function () {
          return isObject$7(this) ? this[TYPED_ARRAY_TAG$1] : undefined;
        }
      });
      for (NAME$1 in TypedArrayConstructorsList) if (globalThis$k[NAME$1]) {
        createNonEnumerableProperty$5(globalThis$k[NAME$1], TYPED_ARRAY_TAG$1, NAME$1);
      }
    }

    var arrayBufferViewCore = {
      NATIVE_ARRAY_BUFFER_VIEWS: NATIVE_ARRAY_BUFFER_VIEWS$3,
      TYPED_ARRAY_TAG: TYPED_ARRAY_TAG_REQUIRED && TYPED_ARRAY_TAG$1,
      aTypedArray: aTypedArray$n,
      aTypedArrayConstructor: aTypedArrayConstructor$2,
      exportTypedArrayMethod: exportTypedArrayMethod$o,
      exportTypedArrayStaticMethod: exportTypedArrayStaticMethod,
      getTypedArrayConstructor: getTypedArrayConstructor$1,
      isView: isView,
      isTypedArray: isTypedArray$1,
      TypedArray: TypedArray$1,
      TypedArrayPrototype: TypedArrayPrototype$2
    };

    /* eslint-disable no-new, sonar/inconsistent-function-call -- required for testing */
    var globalThis$j = globalThis_1;
    var fails$j = fails$C;
    var checkCorrectnessOfIteration$2 = checkCorrectnessOfIteration$3;
    var NATIVE_ARRAY_BUFFER_VIEWS$2 = arrayBufferViewCore.NATIVE_ARRAY_BUFFER_VIEWS;

    var ArrayBuffer$3 = globalThis$j.ArrayBuffer;
    var Int8Array$3 = globalThis$j.Int8Array;

    var typedArrayConstructorsRequireWrappers = !NATIVE_ARRAY_BUFFER_VIEWS$2 || !fails$j(function () {
      Int8Array$3(1);
    }) || !fails$j(function () {
      new Int8Array$3(-1);
    }) || !checkCorrectnessOfIteration$2(function (iterable) {
      new Int8Array$3();
      new Int8Array$3(null);
      new Int8Array$3(1.5);
      new Int8Array$3(iterable);
    }, true) || fails$j(function () {
      // Safari (11+) bug - a reason why even Safari 13 should load a typed array polyfill
      return new Int8Array$3(new ArrayBuffer$3(2), 1, undefined).length !== 1;
    });

    var isObject$6 = isObject$h;

    var floor$2 = Math.floor;

    // `IsIntegralNumber` abstract operation
    // https://tc39.es/ecma262/#sec-isintegralnumber
    // eslint-disable-next-line es/no-number-isinteger -- safe
    var isIntegralNumber$2 = Number.isInteger || function isInteger(it) {
      return !isObject$6(it) && isFinite(it) && floor$2(it) === it;
    };

    var toIntegerOrInfinity$4 = toIntegerOrInfinity$9;

    var $RangeError$1 = RangeError;

    var toPositiveInteger$1 = function (it) {
      var result = toIntegerOrInfinity$4(it);
      if (result < 0) throw new $RangeError$1("The argument can't be less than 0");
      return result;
    };

    var toPositiveInteger = toPositiveInteger$1;

    var $RangeError = RangeError;

    var toOffset$2 = function (it, BYTES) {
      var offset = toPositiveInteger(it);
      if (offset % BYTES) throw new $RangeError('Wrong offset');
      return offset;
    };

    var round = Math.round;

    var toUint8Clamped$1 = function (it) {
      var value = round(it);
      return value < 0 ? 0 : value > 0xFF ? 0xFF : value & 0xFF;
    };

    var uncurryThis$k = functionUncurryThisClause;
    var aCallable$7 = aCallable$a;
    var NATIVE_BIND$1 = functionBindNative;

    var bind$7 = uncurryThis$k(uncurryThis$k.bind);

    // optional / simple context binding
    var functionBindContext = function (fn, that) {
      aCallable$7(fn);
      return that === undefined ? fn : NATIVE_BIND$1 ? bind$7(fn, that) : function (/* ...args */) {
        return fn.apply(that, arguments);
      };
    };

    var classof$9 = classof$f;
    var getMethod$2 = getMethod$4;
    var isNullOrUndefined$1 = isNullOrUndefined$5;
    var Iterators$1 = iterators;
    var wellKnownSymbol$c = wellKnownSymbol$n;

    var ITERATOR$4 = wellKnownSymbol$c('iterator');

    var getIteratorMethod$4 = function (it) {
      if (!isNullOrUndefined$1(it)) return getMethod$2(it, ITERATOR$4)
        || getMethod$2(it, '@@iterator')
        || Iterators$1[classof$9(it)];
    };

    var call$h = functionCall;
    var aCallable$6 = aCallable$a;
    var anObject$6 = anObject$g;
    var tryToString$2 = tryToString$6;
    var getIteratorMethod$3 = getIteratorMethod$4;

    var $TypeError$b = TypeError;

    var getIterator$3 = function (argument, usingIterator) {
      var iteratorMethod = arguments.length < 2 ? getIteratorMethod$3(argument) : usingIterator;
      if (aCallable$6(iteratorMethod)) return anObject$6(call$h(iteratorMethod, argument));
      throw new $TypeError$b(tryToString$2(argument) + ' is not iterable');
    };

    var wellKnownSymbol$b = wellKnownSymbol$n;
    var Iterators = iterators;

    var ITERATOR$3 = wellKnownSymbol$b('iterator');
    var ArrayPrototype = Array.prototype;

    // check on default Array iterator
    var isArrayIteratorMethod$3 = function (it) {
      return it !== undefined && (Iterators.Array === it || ArrayPrototype[ITERATOR$3] === it);
    };

    var classof$8 = classof$f;

    var isBigIntArray$1 = function (it) {
      var klass = classof$8(it);
      return klass === 'BigInt64Array' || klass === 'BigUint64Array';
    };

    var toPrimitive = toPrimitive$3;

    var $TypeError$a = TypeError;

    // `ToBigInt` abstract operation
    // https://tc39.es/ecma262/#sec-tobigint
    var toBigInt$2 = function (argument) {
      var prim = toPrimitive(argument, 'number');
      if (typeof prim == 'number') throw new $TypeError$a("Can't convert number to bigint");
      // eslint-disable-next-line es/no-bigint -- safe
      return BigInt(prim);
    };

    var bind$6 = functionBindContext;
    var call$g = functionCall;
    var aConstructor = aConstructor$2;
    var toObject$8 = toObject$c;
    var lengthOfArrayLike$b = lengthOfArrayLike$e;
    var getIterator$2 = getIterator$3;
    var getIteratorMethod$2 = getIteratorMethod$4;
    var isArrayIteratorMethod$2 = isArrayIteratorMethod$3;
    var isBigIntArray = isBigIntArray$1;
    var aTypedArrayConstructor$1 = arrayBufferViewCore.aTypedArrayConstructor;
    var toBigInt$1 = toBigInt$2;

    var typedArrayFrom$1 = function from(source /* , mapfn, thisArg */) {
      var C = aConstructor(this);
      var O = toObject$8(source);
      var argumentsLength = arguments.length;
      var mapfn = argumentsLength > 1 ? arguments[1] : undefined;
      var mapping = mapfn !== undefined;
      var iteratorMethod = getIteratorMethod$2(O);
      var i, length, result, thisIsBigIntArray, value, step, iterator, next;
      if (iteratorMethod && !isArrayIteratorMethod$2(iteratorMethod)) {
        iterator = getIterator$2(O, iteratorMethod);
        next = iterator.next;
        O = [];
        while (!(step = call$g(next, iterator)).done) {
          O.push(step.value);
        }
      }
      if (mapping && argumentsLength > 2) {
        mapfn = bind$6(mapfn, arguments[2]);
      }
      length = lengthOfArrayLike$b(O);
      result = new (aTypedArrayConstructor$1(C))(length);
      thisIsBigIntArray = isBigIntArray(result);
      for (i = 0; length > i; i++) {
        value = mapping ? mapfn(O[i], i) : O[i];
        // FF30- typed arrays doesn't properly convert objects to typed array values
        result[i] = thisIsBigIntArray ? toBigInt$1(value) : +value;
      }
      return result;
    };

    var classof$7 = classofRaw$2;

    // `IsArray` abstract operation
    // https://tc39.es/ecma262/#sec-isarray
    // eslint-disable-next-line es/no-array-isarray -- safe
    var isArray$4 = Array.isArray || function isArray(argument) {
      return classof$7(argument) === 'Array';
    };

    var isArray$3 = isArray$4;
    var isConstructor$2 = isConstructor$4;
    var isObject$5 = isObject$h;
    var wellKnownSymbol$a = wellKnownSymbol$n;

    var SPECIES$5 = wellKnownSymbol$a('species');
    var $Array$2 = Array;

    // a part of `ArraySpeciesCreate` abstract operation
    // https://tc39.es/ecma262/#sec-arrayspeciescreate
    var arraySpeciesConstructor$1 = function (originalArray) {
      var C;
      if (isArray$3(originalArray)) {
        C = originalArray.constructor;
        // cross-realm fallback
        if (isConstructor$2(C) && (C === $Array$2 || isArray$3(C.prototype))) C = undefined;
        else if (isObject$5(C)) {
          C = C[SPECIES$5];
          if (C === null) C = undefined;
        }
      } return C === undefined ? $Array$2 : C;
    };

    var arraySpeciesConstructor = arraySpeciesConstructor$1;

    // `ArraySpeciesCreate` abstract operation
    // https://tc39.es/ecma262/#sec-arrayspeciescreate
    var arraySpeciesCreate$2 = function (originalArray, length) {
      return new (arraySpeciesConstructor(originalArray))(length === 0 ? 0 : length);
    };

    var bind$5 = functionBindContext;
    var uncurryThis$j = functionUncurryThis;
    var IndexedObject$3 = indexedObject;
    var toObject$7 = toObject$c;
    var lengthOfArrayLike$a = lengthOfArrayLike$e;
    var arraySpeciesCreate$1 = arraySpeciesCreate$2;

    var push$2 = uncurryThis$j([].push);

    // `Array.prototype.{ forEach, map, filter, some, every, find, findIndex, filterReject }` methods implementation
    var createMethod$3 = function (TYPE) {
      var IS_MAP = TYPE === 1;
      var IS_FILTER = TYPE === 2;
      var IS_SOME = TYPE === 3;
      var IS_EVERY = TYPE === 4;
      var IS_FIND_INDEX = TYPE === 6;
      var IS_FILTER_REJECT = TYPE === 7;
      var NO_HOLES = TYPE === 5 || IS_FIND_INDEX;
      return function ($this, callbackfn, that, specificCreate) {
        var O = toObject$7($this);
        var self = IndexedObject$3(O);
        var length = lengthOfArrayLike$a(self);
        var boundFunction = bind$5(callbackfn, that);
        var index = 0;
        var create = specificCreate || arraySpeciesCreate$1;
        var target = IS_MAP ? create($this, length) : IS_FILTER || IS_FILTER_REJECT ? create($this, 0) : undefined;
        var value, result;
        for (;length > index; index++) if (NO_HOLES || index in self) {
          value = self[index];
          result = boundFunction(value, index, O);
          if (TYPE) {
            if (IS_MAP) target[index] = result; // map
            else if (result) switch (TYPE) {
              case 3: return true;              // some
              case 5: return value;             // find
              case 6: return index;             // findIndex
              case 2: push$2(target, value);      // filter
            } else switch (TYPE) {
              case 4: return false;             // every
              case 7: push$2(target, value);      // filterReject
            }
          }
        }
        return IS_FIND_INDEX ? -1 : IS_SOME || IS_EVERY ? IS_EVERY : target;
      };
    };

    var arrayIteration = {
      // `Array.prototype.forEach` method
      // https://tc39.es/ecma262/#sec-array.prototype.foreach
      forEach: createMethod$3(0),
      // `Array.prototype.map` method
      // https://tc39.es/ecma262/#sec-array.prototype.map
      map: createMethod$3(1),
      // `Array.prototype.filter` method
      // https://tc39.es/ecma262/#sec-array.prototype.filter
      filter: createMethod$3(2),
      // `Array.prototype.some` method
      // https://tc39.es/ecma262/#sec-array.prototype.some
      some: createMethod$3(3),
      // `Array.prototype.every` method
      // https://tc39.es/ecma262/#sec-array.prototype.every
      every: createMethod$3(4),
      // `Array.prototype.find` method
      // https://tc39.es/ecma262/#sec-array.prototype.find
      find: createMethod$3(5),
      // `Array.prototype.findIndex` method
      // https://tc39.es/ecma262/#sec-array.prototype.findIndex
      findIndex: createMethod$3(6),
      // `Array.prototype.filterReject` method
      // https://github.com/tc39/proposal-array-filtering
      filterReject: createMethod$3(7)
    };

    var getBuiltIn$3 = getBuiltIn$8;
    var defineBuiltInAccessor$3 = defineBuiltInAccessor$6;
    var wellKnownSymbol$9 = wellKnownSymbol$n;
    var DESCRIPTORS$9 = descriptors;

    var SPECIES$4 = wellKnownSymbol$9('species');

    var setSpecies$4 = function (CONSTRUCTOR_NAME) {
      var Constructor = getBuiltIn$3(CONSTRUCTOR_NAME);

      if (DESCRIPTORS$9 && Constructor && !Constructor[SPECIES$4]) {
        defineBuiltInAccessor$3(Constructor, SPECIES$4, {
          configurable: true,
          get: function () { return this; }
        });
      }
    };

    var lengthOfArrayLike$9 = lengthOfArrayLike$e;

    var arrayFromConstructorAndList$2 = function (Constructor, list, $length) {
      var index = 0;
      var length = arguments.length > 2 ? $length : lengthOfArrayLike$9(list);
      var result = new Constructor(length);
      while (length > index) result[index] = list[index++];
      return result;
    };

    var $$u = _export;
    var globalThis$i = globalThis_1;
    var call$f = functionCall;
    var DESCRIPTORS$8 = descriptors;
    var TYPED_ARRAYS_CONSTRUCTORS_REQUIRES_WRAPPERS = typedArrayConstructorsRequireWrappers;
    var ArrayBufferViewCore$p = arrayBufferViewCore;
    var ArrayBufferModule = arrayBuffer;
    var anInstance$1 = anInstance$3;
    var createPropertyDescriptor$1 = createPropertyDescriptor$5;
    var createNonEnumerableProperty$4 = createNonEnumerableProperty$a;
    var isIntegralNumber$1 = isIntegralNumber$2;
    var toLength$4 = toLength$9;
    var toIndex = toIndex$2;
    var toOffset$1 = toOffset$2;
    var toUint8Clamped = toUint8Clamped$1;
    var toPropertyKey = toPropertyKey$3;
    var hasOwn$2 = hasOwnProperty_1;
    var classof$6 = classof$f;
    var isObject$4 = isObject$h;
    var isSymbol$1 = isSymbol$5;
    var create$1 = objectCreate;
    var isPrototypeOf$2 = objectIsPrototypeOf;
    var setPrototypeOf$1 = objectSetPrototypeOf;
    var getOwnPropertyNames$1 = objectGetOwnPropertyNames.f;
    var typedArrayFrom = typedArrayFrom$1;
    var forEach$1 = arrayIteration.forEach;
    var setSpecies$3 = setSpecies$4;
    var defineBuiltInAccessor$2 = defineBuiltInAccessor$6;
    var definePropertyModule$1 = objectDefineProperty;
    var getOwnPropertyDescriptorModule = objectGetOwnPropertyDescriptor;
    var arrayFromConstructorAndList$1 = arrayFromConstructorAndList$2;
    var InternalStateModule$2 = internalState;
    var inheritIfRequired$1 = inheritIfRequired$4;

    var getInternalState$2 = InternalStateModule$2.get;
    var setInternalState$2 = InternalStateModule$2.set;
    var enforceInternalState$1 = InternalStateModule$2.enforce;
    var nativeDefineProperty = definePropertyModule$1.f;
    var nativeGetOwnPropertyDescriptor = getOwnPropertyDescriptorModule.f;
    var RangeError$2 = globalThis$i.RangeError;
    var ArrayBuffer$2 = ArrayBufferModule.ArrayBuffer;
    var ArrayBufferPrototype = ArrayBuffer$2.prototype;
    var DataView$1 = ArrayBufferModule.DataView;
    var NATIVE_ARRAY_BUFFER_VIEWS$1 = ArrayBufferViewCore$p.NATIVE_ARRAY_BUFFER_VIEWS;
    var TYPED_ARRAY_TAG = ArrayBufferViewCore$p.TYPED_ARRAY_TAG;
    var TypedArray = ArrayBufferViewCore$p.TypedArray;
    var TypedArrayPrototype$1 = ArrayBufferViewCore$p.TypedArrayPrototype;
    var isTypedArray = ArrayBufferViewCore$p.isTypedArray;
    var BYTES_PER_ELEMENT = 'BYTES_PER_ELEMENT';
    var WRONG_LENGTH = 'Wrong length';

    var addGetter = function (it, key) {
      defineBuiltInAccessor$2(it, key, {
        configurable: true,
        get: function () {
          return getInternalState$2(this)[key];
        }
      });
    };

    var isArrayBuffer = function (it) {
      var klass;
      return isPrototypeOf$2(ArrayBufferPrototype, it) || (klass = classof$6(it)) === 'ArrayBuffer' || klass === 'SharedArrayBuffer';
    };

    var isTypedArrayIndex = function (target, key) {
      return isTypedArray(target)
        && !isSymbol$1(key)
        && key in target
        && isIntegralNumber$1(+key)
        && key >= 0;
    };

    var wrappedGetOwnPropertyDescriptor = function getOwnPropertyDescriptor(target, key) {
      key = toPropertyKey(key);
      return isTypedArrayIndex(target, key)
        ? createPropertyDescriptor$1(2, target[key])
        : nativeGetOwnPropertyDescriptor(target, key);
    };

    var wrappedDefineProperty = function defineProperty(target, key, descriptor) {
      key = toPropertyKey(key);
      if (isTypedArrayIndex(target, key)
        && isObject$4(descriptor)
        && hasOwn$2(descriptor, 'value')
        && !hasOwn$2(descriptor, 'get')
        && !hasOwn$2(descriptor, 'set')
        // TODO: add validation descriptor w/o calling accessors
        && !descriptor.configurable
        && (!hasOwn$2(descriptor, 'writable') || descriptor.writable)
        && (!hasOwn$2(descriptor, 'enumerable') || descriptor.enumerable)
      ) {
        target[key] = descriptor.value;
        return target;
      } return nativeDefineProperty(target, key, descriptor);
    };

    if (DESCRIPTORS$8) {
      if (!NATIVE_ARRAY_BUFFER_VIEWS$1) {
        getOwnPropertyDescriptorModule.f = wrappedGetOwnPropertyDescriptor;
        definePropertyModule$1.f = wrappedDefineProperty;
        addGetter(TypedArrayPrototype$1, 'buffer');
        addGetter(TypedArrayPrototype$1, 'byteOffset');
        addGetter(TypedArrayPrototype$1, 'byteLength');
        addGetter(TypedArrayPrototype$1, 'length');
      }

      $$u({ target: 'Object', stat: true, forced: !NATIVE_ARRAY_BUFFER_VIEWS$1 }, {
        getOwnPropertyDescriptor: wrappedGetOwnPropertyDescriptor,
        defineProperty: wrappedDefineProperty
      });

      typedArrayConstructor.exports = function (TYPE, wrapper, CLAMPED) {
        var BYTES = TYPE.match(/\d+/)[0] / 8;
        var CONSTRUCTOR_NAME = TYPE + (CLAMPED ? 'Clamped' : '') + 'Array';
        var GETTER = 'get' + TYPE;
        var SETTER = 'set' + TYPE;
        var NativeTypedArrayConstructor = globalThis$i[CONSTRUCTOR_NAME];
        var TypedArrayConstructor = NativeTypedArrayConstructor;
        var TypedArrayConstructorPrototype = TypedArrayConstructor && TypedArrayConstructor.prototype;
        var exported = {};

        var getter = function (that, index) {
          var data = getInternalState$2(that);
          return data.view[GETTER](index * BYTES + data.byteOffset, true);
        };

        var setter = function (that, index, value) {
          var data = getInternalState$2(that);
          data.view[SETTER](index * BYTES + data.byteOffset, CLAMPED ? toUint8Clamped(value) : value, true);
        };

        var addElement = function (that, index) {
          nativeDefineProperty(that, index, {
            get: function () {
              return getter(this, index);
            },
            set: function (value) {
              return setter(this, index, value);
            },
            enumerable: true
          });
        };

        if (!NATIVE_ARRAY_BUFFER_VIEWS$1) {
          TypedArrayConstructor = wrapper(function (that, data, offset, $length) {
            anInstance$1(that, TypedArrayConstructorPrototype);
            var index = 0;
            var byteOffset = 0;
            var buffer, byteLength, length;
            if (!isObject$4(data)) {
              length = toIndex(data);
              byteLength = length * BYTES;
              buffer = new ArrayBuffer$2(byteLength);
            } else if (isArrayBuffer(data)) {
              buffer = data;
              byteOffset = toOffset$1(offset, BYTES);
              var $len = data.byteLength;
              if ($length === undefined) {
                if ($len % BYTES) throw new RangeError$2(WRONG_LENGTH);
                byteLength = $len - byteOffset;
                if (byteLength < 0) throw new RangeError$2(WRONG_LENGTH);
              } else {
                byteLength = toLength$4($length) * BYTES;
                if (byteLength + byteOffset > $len) throw new RangeError$2(WRONG_LENGTH);
              }
              length = byteLength / BYTES;
            } else if (isTypedArray(data)) {
              return arrayFromConstructorAndList$1(TypedArrayConstructor, data);
            } else {
              return call$f(typedArrayFrom, TypedArrayConstructor, data);
            }
            setInternalState$2(that, {
              buffer: buffer,
              byteOffset: byteOffset,
              byteLength: byteLength,
              length: length,
              view: new DataView$1(buffer)
            });
            while (index < length) addElement(that, index++);
          });

          if (setPrototypeOf$1) setPrototypeOf$1(TypedArrayConstructor, TypedArray);
          TypedArrayConstructorPrototype = TypedArrayConstructor.prototype = create$1(TypedArrayPrototype$1);
        } else if (TYPED_ARRAYS_CONSTRUCTORS_REQUIRES_WRAPPERS) {
          TypedArrayConstructor = wrapper(function (dummy, data, typedArrayOffset, $length) {
            anInstance$1(dummy, TypedArrayConstructorPrototype);
            return inheritIfRequired$1(function () {
              if (!isObject$4(data)) return new NativeTypedArrayConstructor(toIndex(data));
              if (isArrayBuffer(data)) return $length !== undefined
                ? new NativeTypedArrayConstructor(data, toOffset$1(typedArrayOffset, BYTES), $length)
                : typedArrayOffset !== undefined
                  ? new NativeTypedArrayConstructor(data, toOffset$1(typedArrayOffset, BYTES))
                  : new NativeTypedArrayConstructor(data);
              if (isTypedArray(data)) return arrayFromConstructorAndList$1(TypedArrayConstructor, data);
              return call$f(typedArrayFrom, TypedArrayConstructor, data);
            }(), dummy, TypedArrayConstructor);
          });

          if (setPrototypeOf$1) setPrototypeOf$1(TypedArrayConstructor, TypedArray);
          forEach$1(getOwnPropertyNames$1(NativeTypedArrayConstructor), function (key) {
            if (!(key in TypedArrayConstructor)) {
              createNonEnumerableProperty$4(TypedArrayConstructor, key, NativeTypedArrayConstructor[key]);
            }
          });
          TypedArrayConstructor.prototype = TypedArrayConstructorPrototype;
        }

        if (TypedArrayConstructorPrototype.constructor !== TypedArrayConstructor) {
          createNonEnumerableProperty$4(TypedArrayConstructorPrototype, 'constructor', TypedArrayConstructor);
        }

        enforceInternalState$1(TypedArrayConstructorPrototype).TypedArrayConstructor = TypedArrayConstructor;

        if (TYPED_ARRAY_TAG) {
          createNonEnumerableProperty$4(TypedArrayConstructorPrototype, TYPED_ARRAY_TAG, CONSTRUCTOR_NAME);
        }

        var FORCED = TypedArrayConstructor !== NativeTypedArrayConstructor;

        exported[CONSTRUCTOR_NAME] = TypedArrayConstructor;

        $$u({ global: true, constructor: true, forced: FORCED, sham: !NATIVE_ARRAY_BUFFER_VIEWS$1 }, exported);

        if (!(BYTES_PER_ELEMENT in TypedArrayConstructor)) {
          createNonEnumerableProperty$4(TypedArrayConstructor, BYTES_PER_ELEMENT, BYTES);
        }

        if (!(BYTES_PER_ELEMENT in TypedArrayConstructorPrototype)) {
          createNonEnumerableProperty$4(TypedArrayConstructorPrototype, BYTES_PER_ELEMENT, BYTES);
        }

        setSpecies$3(CONSTRUCTOR_NAME);
      };
    } else typedArrayConstructor.exports = function () { /* empty */ };

    var createTypedArrayConstructor$7 = typedArrayConstructor.exports;

    // `Uint8Array` constructor
    // https://tc39.es/ecma262/#sec-typedarray-objects
    createTypedArrayConstructor$7('Uint8', function (init) {
      return function Uint8Array(data, byteOffset, length) {
        return init(this, data, byteOffset, length);
      };
    });

    var ArrayBufferViewCore$o = arrayBufferViewCore;
    var lengthOfArrayLike$8 = lengthOfArrayLike$e;
    var toIntegerOrInfinity$3 = toIntegerOrInfinity$9;

    var aTypedArray$m = ArrayBufferViewCore$o.aTypedArray;
    var exportTypedArrayMethod$n = ArrayBufferViewCore$o.exportTypedArrayMethod;

    // `%TypedArray%.prototype.at` method
    // https://tc39.es/ecma262/#sec-%typedarray%.prototype.at
    exportTypedArrayMethod$n('at', function at(index) {
      var O = aTypedArray$m(this);
      var len = lengthOfArrayLike$8(O);
      var relativeIndex = toIntegerOrInfinity$3(index);
      var k = relativeIndex >= 0 ? relativeIndex : len + relativeIndex;
      return (k < 0 || k >= len) ? undefined : O[k];
    });

    var tryToString$1 = tryToString$6;

    var $TypeError$9 = TypeError;

    var deletePropertyOrThrow$2 = function (O, P) {
      if (!delete O[P]) throw new $TypeError$9('Cannot delete property ' + tryToString$1(P) + ' of ' + tryToString$1(O));
    };

    var toObject$6 = toObject$c;
    var toAbsoluteIndex$3 = toAbsoluteIndex$7;
    var lengthOfArrayLike$7 = lengthOfArrayLike$e;
    var deletePropertyOrThrow$1 = deletePropertyOrThrow$2;

    var min$4 = Math.min;

    // `Array.prototype.copyWithin` method implementation
    // https://tc39.es/ecma262/#sec-array.prototype.copywithin
    // eslint-disable-next-line es/no-array-prototype-copywithin -- safe
    var arrayCopyWithin = [].copyWithin || function copyWithin(target /* = 0 */, start /* = 0, end = @length */) {
      var O = toObject$6(this);
      var len = lengthOfArrayLike$7(O);
      var to = toAbsoluteIndex$3(target, len);
      var from = toAbsoluteIndex$3(start, len);
      var end = arguments.length > 2 ? arguments[2] : undefined;
      var count = min$4((end === undefined ? len : toAbsoluteIndex$3(end, len)) - from, len - to);
      var inc = 1;
      if (from < to && to < from + count) {
        inc = -1;
        from += count - 1;
        to += count - 1;
      }
      while (count-- > 0) {
        if (from in O) O[to] = O[from];
        else deletePropertyOrThrow$1(O, to);
        to += inc;
        from += inc;
      } return O;
    };

    var uncurryThis$i = functionUncurryThis;
    var ArrayBufferViewCore$n = arrayBufferViewCore;
    var $ArrayCopyWithin = arrayCopyWithin;

    var u$ArrayCopyWithin = uncurryThis$i($ArrayCopyWithin);
    var aTypedArray$l = ArrayBufferViewCore$n.aTypedArray;
    var exportTypedArrayMethod$m = ArrayBufferViewCore$n.exportTypedArrayMethod;

    // `%TypedArray%.prototype.copyWithin` method
    // https://tc39.es/ecma262/#sec-%typedarray%.prototype.copywithin
    exportTypedArrayMethod$m('copyWithin', function copyWithin(target, start /* , end */) {
      return u$ArrayCopyWithin(aTypedArray$l(this), target, start, arguments.length > 2 ? arguments[2] : undefined);
    });

    var ArrayBufferViewCore$m = arrayBufferViewCore;
    var $every = arrayIteration.every;

    var aTypedArray$k = ArrayBufferViewCore$m.aTypedArray;
    var exportTypedArrayMethod$l = ArrayBufferViewCore$m.exportTypedArrayMethod;

    // `%TypedArray%.prototype.every` method
    // https://tc39.es/ecma262/#sec-%typedarray%.prototype.every
    exportTypedArrayMethod$l('every', function every(callbackfn /* , thisArg */) {
      return $every(aTypedArray$k(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined);
    });

    var ArrayBufferViewCore$l = arrayBufferViewCore;
    var $fill = arrayFill$1;
    var toBigInt = toBigInt$2;
    var classof$5 = classof$f;
    var call$e = functionCall;
    var uncurryThis$h = functionUncurryThis;
    var fails$i = fails$C;

    var aTypedArray$j = ArrayBufferViewCore$l.aTypedArray;
    var exportTypedArrayMethod$k = ArrayBufferViewCore$l.exportTypedArrayMethod;
    var slice$1 = uncurryThis$h(''.slice);

    // V8 ~ Chrome < 59, Safari < 14.1, FF < 55, Edge <=18
    var CONVERSION_BUG = fails$i(function () {
      var count = 0;
      // eslint-disable-next-line es/no-typed-arrays -- safe
      new Int8Array(2).fill({ valueOf: function () { return count++; } });
      return count !== 1;
    });

    // `%TypedArray%.prototype.fill` method
    // https://tc39.es/ecma262/#sec-%typedarray%.prototype.fill
    exportTypedArrayMethod$k('fill', function fill(value /* , start, end */) {
      var length = arguments.length;
      aTypedArray$j(this);
      var actualValue = slice$1(classof$5(this), 0, 3) === 'Big' ? toBigInt(value) : +value;
      return call$e($fill, this, actualValue, length > 1 ? arguments[1] : undefined, length > 2 ? arguments[2] : undefined);
    }, CONVERSION_BUG);

    var ArrayBufferViewCore$k = arrayBufferViewCore;
    var speciesConstructor$1 = speciesConstructor$3;

    var aTypedArrayConstructor = ArrayBufferViewCore$k.aTypedArrayConstructor;
    var getTypedArrayConstructor = ArrayBufferViewCore$k.getTypedArrayConstructor;

    // a part of `TypedArraySpeciesCreate` abstract operation
    // https://tc39.es/ecma262/#typedarray-species-create
    var typedArraySpeciesConstructor$4 = function (originalArray) {
      return aTypedArrayConstructor(speciesConstructor$1(originalArray, getTypedArrayConstructor(originalArray)));
    };

    var arrayFromConstructorAndList = arrayFromConstructorAndList$2;
    var typedArraySpeciesConstructor$3 = typedArraySpeciesConstructor$4;

    var typedArrayFromSpeciesAndList = function (instance, list) {
      return arrayFromConstructorAndList(typedArraySpeciesConstructor$3(instance), list);
    };

    var ArrayBufferViewCore$j = arrayBufferViewCore;
    var $filter$1 = arrayIteration.filter;
    var fromSpeciesAndList = typedArrayFromSpeciesAndList;

    var aTypedArray$i = ArrayBufferViewCore$j.aTypedArray;
    var exportTypedArrayMethod$j = ArrayBufferViewCore$j.exportTypedArrayMethod;

    // `%TypedArray%.prototype.filter` method
    // https://tc39.es/ecma262/#sec-%typedarray%.prototype.filter
    exportTypedArrayMethod$j('filter', function filter(callbackfn /* , thisArg */) {
      var list = $filter$1(aTypedArray$i(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined);
      return fromSpeciesAndList(this, list);
    });

    var ArrayBufferViewCore$i = arrayBufferViewCore;
    var $find$1 = arrayIteration.find;

    var aTypedArray$h = ArrayBufferViewCore$i.aTypedArray;
    var exportTypedArrayMethod$i = ArrayBufferViewCore$i.exportTypedArrayMethod;

    // `%TypedArray%.prototype.find` method
    // https://tc39.es/ecma262/#sec-%typedarray%.prototype.find
    exportTypedArrayMethod$i('find', function find(predicate /* , thisArg */) {
      return $find$1(aTypedArray$h(this), predicate, arguments.length > 1 ? arguments[1] : undefined);
    });

    var ArrayBufferViewCore$h = arrayBufferViewCore;
    var $findIndex$1 = arrayIteration.findIndex;

    var aTypedArray$g = ArrayBufferViewCore$h.aTypedArray;
    var exportTypedArrayMethod$h = ArrayBufferViewCore$h.exportTypedArrayMethod;

    // `%TypedArray%.prototype.findIndex` method
    // https://tc39.es/ecma262/#sec-%typedarray%.prototype.findindex
    exportTypedArrayMethod$h('findIndex', function findIndex(predicate /* , thisArg */) {
      return $findIndex$1(aTypedArray$g(this), predicate, arguments.length > 1 ? arguments[1] : undefined);
    });

    var ArrayBufferViewCore$g = arrayBufferViewCore;
    var $forEach$1 = arrayIteration.forEach;

    var aTypedArray$f = ArrayBufferViewCore$g.aTypedArray;
    var exportTypedArrayMethod$g = ArrayBufferViewCore$g.exportTypedArrayMethod;

    // `%TypedArray%.prototype.forEach` method
    // https://tc39.es/ecma262/#sec-%typedarray%.prototype.foreach
    exportTypedArrayMethod$g('forEach', function forEach(callbackfn /* , thisArg */) {
      $forEach$1(aTypedArray$f(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined);
    });

    var ArrayBufferViewCore$f = arrayBufferViewCore;
    var $includes$1 = arrayIncludes.includes;

    var aTypedArray$e = ArrayBufferViewCore$f.aTypedArray;
    var exportTypedArrayMethod$f = ArrayBufferViewCore$f.exportTypedArrayMethod;

    // `%TypedArray%.prototype.includes` method
    // https://tc39.es/ecma262/#sec-%typedarray%.prototype.includes
    exportTypedArrayMethod$f('includes', function includes(searchElement /* , fromIndex */) {
      return $includes$1(aTypedArray$e(this), searchElement, arguments.length > 1 ? arguments[1] : undefined);
    });

    var ArrayBufferViewCore$e = arrayBufferViewCore;
    var $indexOf$1 = arrayIncludes.indexOf;

    var aTypedArray$d = ArrayBufferViewCore$e.aTypedArray;
    var exportTypedArrayMethod$e = ArrayBufferViewCore$e.exportTypedArrayMethod;

    // `%TypedArray%.prototype.indexOf` method
    // https://tc39.es/ecma262/#sec-%typedarray%.prototype.indexof
    exportTypedArrayMethod$e('indexOf', function indexOf(searchElement /* , fromIndex */) {
      return $indexOf$1(aTypedArray$d(this), searchElement, arguments.length > 1 ? arguments[1] : undefined);
    });

    var globalThis$h = globalThis_1;
    var fails$h = fails$C;
    var uncurryThis$g = functionUncurryThis;
    var ArrayBufferViewCore$d = arrayBufferViewCore;
    var ArrayIterators = es_array_iterator;
    var wellKnownSymbol$8 = wellKnownSymbol$n;

    var ITERATOR$2 = wellKnownSymbol$8('iterator');
    var Uint8Array$2 = globalThis$h.Uint8Array;
    var arrayValues = uncurryThis$g(ArrayIterators.values);
    var arrayKeys = uncurryThis$g(ArrayIterators.keys);
    var arrayEntries = uncurryThis$g(ArrayIterators.entries);
    var aTypedArray$c = ArrayBufferViewCore$d.aTypedArray;
    var exportTypedArrayMethod$d = ArrayBufferViewCore$d.exportTypedArrayMethod;
    var TypedArrayPrototype = Uint8Array$2 && Uint8Array$2.prototype;

    var GENERIC = !fails$h(function () {
      TypedArrayPrototype[ITERATOR$2].call([1]);
    });

    var ITERATOR_IS_VALUES = !!TypedArrayPrototype
      && TypedArrayPrototype.values
      && TypedArrayPrototype[ITERATOR$2] === TypedArrayPrototype.values
      && TypedArrayPrototype.values.name === 'values';

    var typedArrayValues = function values() {
      return arrayValues(aTypedArray$c(this));
    };

    // `%TypedArray%.prototype.entries` method
    // https://tc39.es/ecma262/#sec-%typedarray%.prototype.entries
    exportTypedArrayMethod$d('entries', function entries() {
      return arrayEntries(aTypedArray$c(this));
    }, GENERIC);
    // `%TypedArray%.prototype.keys` method
    // https://tc39.es/ecma262/#sec-%typedarray%.prototype.keys
    exportTypedArrayMethod$d('keys', function keys() {
      return arrayKeys(aTypedArray$c(this));
    }, GENERIC);
    // `%TypedArray%.prototype.values` method
    // https://tc39.es/ecma262/#sec-%typedarray%.prototype.values
    exportTypedArrayMethod$d('values', typedArrayValues, GENERIC || !ITERATOR_IS_VALUES, { name: 'values' });
    // `%TypedArray%.prototype[@@iterator]` method
    // https://tc39.es/ecma262/#sec-%typedarray%.prototype-@@iterator
    exportTypedArrayMethod$d(ITERATOR$2, typedArrayValues, GENERIC || !ITERATOR_IS_VALUES, { name: 'values' });

    var ArrayBufferViewCore$c = arrayBufferViewCore;
    var uncurryThis$f = functionUncurryThis;

    var aTypedArray$b = ArrayBufferViewCore$c.aTypedArray;
    var exportTypedArrayMethod$c = ArrayBufferViewCore$c.exportTypedArrayMethod;
    var $join = uncurryThis$f([].join);

    // `%TypedArray%.prototype.join` method
    // https://tc39.es/ecma262/#sec-%typedarray%.prototype.join
    exportTypedArrayMethod$c('join', function join(separator) {
      return $join(aTypedArray$b(this), separator);
    });

    var NATIVE_BIND = functionBindNative;

    var FunctionPrototype$1 = Function.prototype;
    var apply$5 = FunctionPrototype$1.apply;
    var call$d = FunctionPrototype$1.call;

    // eslint-disable-next-line es/no-reflect -- safe
    var functionApply = typeof Reflect == 'object' && Reflect.apply || (NATIVE_BIND ? call$d.bind(apply$5) : function () {
      return call$d.apply(apply$5, arguments);
    });

    var fails$g = fails$C;

    var arrayMethodIsStrict$4 = function (METHOD_NAME, argument) {
      var method = [][METHOD_NAME];
      return !!method && fails$g(function () {
        // eslint-disable-next-line no-useless-call -- required for testing
        method.call(null, argument || function () { return 1; }, 1);
      });
    };

    /* eslint-disable es/no-array-prototype-lastindexof -- safe */
    var apply$4 = functionApply;
    var toIndexedObject$4 = toIndexedObject$a;
    var toIntegerOrInfinity$2 = toIntegerOrInfinity$9;
    var lengthOfArrayLike$6 = lengthOfArrayLike$e;
    var arrayMethodIsStrict$3 = arrayMethodIsStrict$4;

    var min$3 = Math.min;
    var $lastIndexOf$1 = [].lastIndexOf;
    var NEGATIVE_ZERO$1 = !!$lastIndexOf$1 && 1 / [1].lastIndexOf(1, -0) < 0;
    var STRICT_METHOD$1 = arrayMethodIsStrict$3('lastIndexOf');
    var FORCED$5 = NEGATIVE_ZERO$1 || !STRICT_METHOD$1;

    // `Array.prototype.lastIndexOf` method implementation
    // https://tc39.es/ecma262/#sec-array.prototype.lastindexof
    var arrayLastIndexOf = FORCED$5 ? function lastIndexOf(searchElement /* , fromIndex = @[*-1] */) {
      // convert -0 to +0
      if (NEGATIVE_ZERO$1) return apply$4($lastIndexOf$1, this, arguments) || 0;
      var O = toIndexedObject$4(this);
      var length = lengthOfArrayLike$6(O);
      if (length === 0) return -1;
      var index = length - 1;
      if (arguments.length > 1) index = min$3(index, toIntegerOrInfinity$2(arguments[1]));
      if (index < 0) index = length + index;
      for (;index >= 0; index--) if (index in O && O[index] === searchElement) return index || 0;
      return -1;
    } : $lastIndexOf$1;

    var ArrayBufferViewCore$b = arrayBufferViewCore;
    var apply$3 = functionApply;
    var $lastIndexOf = arrayLastIndexOf;

    var aTypedArray$a = ArrayBufferViewCore$b.aTypedArray;
    var exportTypedArrayMethod$b = ArrayBufferViewCore$b.exportTypedArrayMethod;

    // `%TypedArray%.prototype.lastIndexOf` method
    // https://tc39.es/ecma262/#sec-%typedarray%.prototype.lastindexof
    exportTypedArrayMethod$b('lastIndexOf', function lastIndexOf(searchElement /* , fromIndex */) {
      var length = arguments.length;
      return apply$3($lastIndexOf, aTypedArray$a(this), length > 1 ? [searchElement, arguments[1]] : [searchElement]);
    });

    var ArrayBufferViewCore$a = arrayBufferViewCore;
    var $map$1 = arrayIteration.map;
    var typedArraySpeciesConstructor$2 = typedArraySpeciesConstructor$4;

    var aTypedArray$9 = ArrayBufferViewCore$a.aTypedArray;
    var exportTypedArrayMethod$a = ArrayBufferViewCore$a.exportTypedArrayMethod;

    // `%TypedArray%.prototype.map` method
    // https://tc39.es/ecma262/#sec-%typedarray%.prototype.map
    exportTypedArrayMethod$a('map', function map(mapfn /* , thisArg */) {
      return $map$1(aTypedArray$9(this), mapfn, arguments.length > 1 ? arguments[1] : undefined, function (O, length) {
        return new (typedArraySpeciesConstructor$2(O))(length);
      });
    });

    var aCallable$5 = aCallable$a;
    var toObject$5 = toObject$c;
    var IndexedObject$2 = indexedObject;
    var lengthOfArrayLike$5 = lengthOfArrayLike$e;

    var $TypeError$8 = TypeError;

    var REDUCE_EMPTY = 'Reduce of empty array with no initial value';

    // `Array.prototype.{ reduce, reduceRight }` methods implementation
    var createMethod$2 = function (IS_RIGHT) {
      return function (that, callbackfn, argumentsLength, memo) {
        var O = toObject$5(that);
        var self = IndexedObject$2(O);
        var length = lengthOfArrayLike$5(O);
        aCallable$5(callbackfn);
        if (length === 0 && argumentsLength < 2) throw new $TypeError$8(REDUCE_EMPTY);
        var index = IS_RIGHT ? length - 1 : 0;
        var i = IS_RIGHT ? -1 : 1;
        if (argumentsLength < 2) while (true) {
          if (index in self) {
            memo = self[index];
            index += i;
            break;
          }
          index += i;
          if (IS_RIGHT ? index < 0 : length <= index) {
            throw new $TypeError$8(REDUCE_EMPTY);
          }
        }
        for (;IS_RIGHT ? index >= 0 : length > index; index += i) if (index in self) {
          memo = callbackfn(memo, self[index], index, O);
        }
        return memo;
      };
    };

    var arrayReduce = {
      // `Array.prototype.reduce` method
      // https://tc39.es/ecma262/#sec-array.prototype.reduce
      left: createMethod$2(false),
      // `Array.prototype.reduceRight` method
      // https://tc39.es/ecma262/#sec-array.prototype.reduceright
      right: createMethod$2(true)
    };

    var ArrayBufferViewCore$9 = arrayBufferViewCore;
    var $reduce = arrayReduce.left;

    var aTypedArray$8 = ArrayBufferViewCore$9.aTypedArray;
    var exportTypedArrayMethod$9 = ArrayBufferViewCore$9.exportTypedArrayMethod;

    // `%TypedArray%.prototype.reduce` method
    // https://tc39.es/ecma262/#sec-%typedarray%.prototype.reduce
    exportTypedArrayMethod$9('reduce', function reduce(callbackfn /* , initialValue */) {
      var length = arguments.length;
      return $reduce(aTypedArray$8(this), callbackfn, length, length > 1 ? arguments[1] : undefined);
    });

    var ArrayBufferViewCore$8 = arrayBufferViewCore;
    var $reduceRight = arrayReduce.right;

    var aTypedArray$7 = ArrayBufferViewCore$8.aTypedArray;
    var exportTypedArrayMethod$8 = ArrayBufferViewCore$8.exportTypedArrayMethod;

    // `%TypedArray%.prototype.reduceRight` method
    // https://tc39.es/ecma262/#sec-%typedarray%.prototype.reduceright
    exportTypedArrayMethod$8('reduceRight', function reduceRight(callbackfn /* , initialValue */) {
      var length = arguments.length;
      return $reduceRight(aTypedArray$7(this), callbackfn, length, length > 1 ? arguments[1] : undefined);
    });

    var ArrayBufferViewCore$7 = arrayBufferViewCore;

    var aTypedArray$6 = ArrayBufferViewCore$7.aTypedArray;
    var exportTypedArrayMethod$7 = ArrayBufferViewCore$7.exportTypedArrayMethod;
    var floor$1 = Math.floor;

    // `%TypedArray%.prototype.reverse` method
    // https://tc39.es/ecma262/#sec-%typedarray%.prototype.reverse
    exportTypedArrayMethod$7('reverse', function reverse() {
      var that = this;
      var length = aTypedArray$6(that).length;
      var middle = floor$1(length / 2);
      var index = 0;
      var value;
      while (index < middle) {
        value = that[index];
        that[index++] = that[--length];
        that[length] = value;
      } return that;
    });

    var globalThis$g = globalThis_1;
    var call$c = functionCall;
    var ArrayBufferViewCore$6 = arrayBufferViewCore;
    var lengthOfArrayLike$4 = lengthOfArrayLike$e;
    var toOffset = toOffset$2;
    var toIndexedObject$3 = toObject$c;
    var fails$f = fails$C;

    var RangeError$1 = globalThis$g.RangeError;
    var Int8Array$2 = globalThis$g.Int8Array;
    var Int8ArrayPrototype = Int8Array$2 && Int8Array$2.prototype;
    var $set = Int8ArrayPrototype && Int8ArrayPrototype.set;
    var aTypedArray$5 = ArrayBufferViewCore$6.aTypedArray;
    var exportTypedArrayMethod$6 = ArrayBufferViewCore$6.exportTypedArrayMethod;

    var WORKS_WITH_OBJECTS_AND_GENERIC_ON_TYPED_ARRAYS = !fails$f(function () {
      // eslint-disable-next-line es/no-typed-arrays -- required for testing
      var array = new Uint8ClampedArray(2);
      call$c($set, array, { length: 1, 0: 3 }, 1);
      return array[1] !== 3;
    });

    // https://bugs.chromium.org/p/v8/issues/detail?id=11294 and other
    var TO_OBJECT_BUG = WORKS_WITH_OBJECTS_AND_GENERIC_ON_TYPED_ARRAYS && ArrayBufferViewCore$6.NATIVE_ARRAY_BUFFER_VIEWS && fails$f(function () {
      var array = new Int8Array$2(2);
      array.set(1);
      array.set('2', 1);
      return array[0] !== 0 || array[1] !== 2;
    });

    // `%TypedArray%.prototype.set` method
    // https://tc39.es/ecma262/#sec-%typedarray%.prototype.set
    exportTypedArrayMethod$6('set', function set(arrayLike /* , offset */) {
      aTypedArray$5(this);
      var offset = toOffset(arguments.length > 1 ? arguments[1] : undefined, 1);
      var src = toIndexedObject$3(arrayLike);
      if (WORKS_WITH_OBJECTS_AND_GENERIC_ON_TYPED_ARRAYS) return call$c($set, this, src, offset);
      var length = this.length;
      var len = lengthOfArrayLike$4(src);
      var index = 0;
      if (len + offset > length) throw new RangeError$1('Wrong length');
      while (index < len) this[offset + index] = src[index++];
    }, !WORKS_WITH_OBJECTS_AND_GENERIC_ON_TYPED_ARRAYS || TO_OBJECT_BUG);

    var ArrayBufferViewCore$5 = arrayBufferViewCore;
    var typedArraySpeciesConstructor$1 = typedArraySpeciesConstructor$4;
    var fails$e = fails$C;
    var arraySlice$4 = arraySlice$6;

    var aTypedArray$4 = ArrayBufferViewCore$5.aTypedArray;
    var exportTypedArrayMethod$5 = ArrayBufferViewCore$5.exportTypedArrayMethod;

    var FORCED$4 = fails$e(function () {
      // eslint-disable-next-line es/no-typed-arrays -- required for testing
      new Int8Array(1).slice();
    });

    // `%TypedArray%.prototype.slice` method
    // https://tc39.es/ecma262/#sec-%typedarray%.prototype.slice
    exportTypedArrayMethod$5('slice', function slice(start, end) {
      var list = arraySlice$4(aTypedArray$4(this), start, end);
      var C = typedArraySpeciesConstructor$1(this);
      var index = 0;
      var length = list.length;
      var result = new C(length);
      while (length > index) result[index] = list[index++];
      return result;
    }, FORCED$4);

    var ArrayBufferViewCore$4 = arrayBufferViewCore;
    var $some = arrayIteration.some;

    var aTypedArray$3 = ArrayBufferViewCore$4.aTypedArray;
    var exportTypedArrayMethod$4 = ArrayBufferViewCore$4.exportTypedArrayMethod;

    // `%TypedArray%.prototype.some` method
    // https://tc39.es/ecma262/#sec-%typedarray%.prototype.some
    exportTypedArrayMethod$4('some', function some(callbackfn /* , thisArg */) {
      return $some(aTypedArray$3(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined);
    });

    var arraySlice$3 = arraySlice$6;

    var floor = Math.floor;

    var sort = function (array, comparefn) {
      var length = array.length;

      if (length < 8) {
        // insertion sort
        var i = 1;
        var element, j;

        while (i < length) {
          j = i;
          element = array[i];
          while (j && comparefn(array[j - 1], element) > 0) {
            array[j] = array[--j];
          }
          if (j !== i++) array[j] = element;
        }
      } else {
        // merge sort
        var middle = floor(length / 2);
        var left = sort(arraySlice$3(array, 0, middle), comparefn);
        var right = sort(arraySlice$3(array, middle), comparefn);
        var llength = left.length;
        var rlength = right.length;
        var lindex = 0;
        var rindex = 0;

        while (lindex < llength || rindex < rlength) {
          array[lindex + rindex] = (lindex < llength && rindex < rlength)
            ? comparefn(left[lindex], right[rindex]) <= 0 ? left[lindex++] : right[rindex++]
            : lindex < llength ? left[lindex++] : right[rindex++];
        }
      }

      return array;
    };

    var arraySort = sort;

    var userAgent$5 = environmentUserAgent;

    var firefox = userAgent$5.match(/firefox\/(\d+)/i);

    var environmentFfVersion = !!firefox && +firefox[1];

    var UA = environmentUserAgent;

    var environmentIsIeOrEdge = /MSIE|Trident/.test(UA);

    var userAgent$4 = environmentUserAgent;

    var webkit = userAgent$4.match(/AppleWebKit\/(\d+)\./);

    var environmentWebkitVersion = !!webkit && +webkit[1];

    var globalThis$f = globalThis_1;
    var uncurryThis$e = functionUncurryThisClause;
    var fails$d = fails$C;
    var aCallable$4 = aCallable$a;
    var internalSort = arraySort;
    var ArrayBufferViewCore$3 = arrayBufferViewCore;
    var FF = environmentFfVersion;
    var IE_OR_EDGE = environmentIsIeOrEdge;
    var V8 = environmentV8Version;
    var WEBKIT = environmentWebkitVersion;

    var aTypedArray$2 = ArrayBufferViewCore$3.aTypedArray;
    var exportTypedArrayMethod$3 = ArrayBufferViewCore$3.exportTypedArrayMethod;
    var Uint16Array$1 = globalThis$f.Uint16Array;
    var nativeSort = Uint16Array$1 && uncurryThis$e(Uint16Array$1.prototype.sort);

    // WebKit
    var ACCEPT_INCORRECT_ARGUMENTS = !!nativeSort && !(fails$d(function () {
      nativeSort(new Uint16Array$1(2), null);
    }) && fails$d(function () {
      nativeSort(new Uint16Array$1(2), {});
    }));

    var STABLE_SORT = !!nativeSort && !fails$d(function () {
      // feature detection can be too slow, so check engines versions
      if (V8) return V8 < 74;
      if (FF) return FF < 67;
      if (IE_OR_EDGE) return true;
      if (WEBKIT) return WEBKIT < 602;

      var array = new Uint16Array$1(516);
      var expected = Array(516);
      var index, mod;

      for (index = 0; index < 516; index++) {
        mod = index % 4;
        array[index] = 515 - index;
        expected[index] = index - 2 * mod + 3;
      }

      nativeSort(array, function (a, b) {
        return (a / 4 | 0) - (b / 4 | 0);
      });

      for (index = 0; index < 516; index++) {
        if (array[index] !== expected[index]) return true;
      }
    });

    var getSortCompare = function (comparefn) {
      return function (x, y) {
        if (comparefn !== undefined) return +comparefn(x, y) || 0;
        // eslint-disable-next-line no-self-compare -- NaN check
        if (y !== y) return -1;
        // eslint-disable-next-line no-self-compare -- NaN check
        if (x !== x) return 1;
        if (x === 0 && y === 0) return 1 / x > 0 && 1 / y < 0 ? 1 : -1;
        return x > y;
      };
    };

    // `%TypedArray%.prototype.sort` method
    // https://tc39.es/ecma262/#sec-%typedarray%.prototype.sort
    exportTypedArrayMethod$3('sort', function sort(comparefn) {
      if (comparefn !== undefined) aCallable$4(comparefn);
      if (STABLE_SORT) return nativeSort(this, comparefn);

      return internalSort(aTypedArray$2(this), getSortCompare(comparefn));
    }, !STABLE_SORT || ACCEPT_INCORRECT_ARGUMENTS);

    var ArrayBufferViewCore$2 = arrayBufferViewCore;
    var toLength$3 = toLength$9;
    var toAbsoluteIndex$2 = toAbsoluteIndex$7;
    var typedArraySpeciesConstructor = typedArraySpeciesConstructor$4;

    var aTypedArray$1 = ArrayBufferViewCore$2.aTypedArray;
    var exportTypedArrayMethod$2 = ArrayBufferViewCore$2.exportTypedArrayMethod;

    // `%TypedArray%.prototype.subarray` method
    // https://tc39.es/ecma262/#sec-%typedarray%.prototype.subarray
    exportTypedArrayMethod$2('subarray', function subarray(begin, end) {
      var O = aTypedArray$1(this);
      var length = O.length;
      var beginIndex = toAbsoluteIndex$2(begin, length);
      var C = typedArraySpeciesConstructor(O);
      return new C(
        O.buffer,
        O.byteOffset + beginIndex * O.BYTES_PER_ELEMENT,
        toLength$3((end === undefined ? length : toAbsoluteIndex$2(end, length)) - beginIndex)
      );
    });

    var globalThis$e = globalThis_1;
    var apply$2 = functionApply;
    var ArrayBufferViewCore$1 = arrayBufferViewCore;
    var fails$c = fails$C;
    var arraySlice$2 = arraySlice$6;

    var Int8Array$1 = globalThis$e.Int8Array;
    var aTypedArray = ArrayBufferViewCore$1.aTypedArray;
    var exportTypedArrayMethod$1 = ArrayBufferViewCore$1.exportTypedArrayMethod;
    var $toLocaleString = [].toLocaleString;

    // iOS Safari 6.x fails here
    var TO_LOCALE_STRING_BUG = !!Int8Array$1 && fails$c(function () {
      $toLocaleString.call(new Int8Array$1(1));
    });

    var FORCED$3 = fails$c(function () {
      return [1, 2].toLocaleString() !== new Int8Array$1([1, 2]).toLocaleString();
    }) || !fails$c(function () {
      Int8Array$1.prototype.toLocaleString.call([1, 2]);
    });

    // `%TypedArray%.prototype.toLocaleString` method
    // https://tc39.es/ecma262/#sec-%typedarray%.prototype.tolocalestring
    exportTypedArrayMethod$1('toLocaleString', function toLocaleString() {
      return apply$2(
        $toLocaleString,
        TO_LOCALE_STRING_BUG ? arraySlice$2(aTypedArray(this)) : aTypedArray(this),
        arraySlice$2(arguments)
      );
    }, FORCED$3);

    var exportTypedArrayMethod = arrayBufferViewCore.exportTypedArrayMethod;
    var fails$b = fails$C;
    var globalThis$d = globalThis_1;
    var uncurryThis$d = functionUncurryThis;

    var Uint8Array$1 = globalThis$d.Uint8Array;
    var Uint8ArrayPrototype = Uint8Array$1 && Uint8Array$1.prototype || {};
    var arrayToString = [].toString;
    var join = uncurryThis$d([].join);

    if (fails$b(function () { arrayToString.call({}); })) {
      arrayToString = function toString() {
        return join(this);
      };
    }

    var IS_NOT_ARRAY_METHOD = Uint8ArrayPrototype.toString !== arrayToString;

    // `%TypedArray%.prototype.toString` method
    // https://tc39.es/ecma262/#sec-%typedarray%.prototype.tostring
    exportTypedArrayMethod('toString', arrayToString, IS_NOT_ARRAY_METHOD);

    var call$b = functionCall;
    var anObject$5 = anObject$g;
    var getMethod$1 = getMethod$4;

    var iteratorClose$2 = function (iterator, kind, value) {
      var innerResult, innerError;
      anObject$5(iterator);
      try {
        innerResult = getMethod$1(iterator, 'return');
        if (!innerResult) {
          if (kind === 'throw') throw value;
          return value;
        }
        innerResult = call$b(innerResult, iterator);
      } catch (error) {
        innerError = true;
        innerResult = error;
      }
      if (kind === 'throw') throw value;
      if (innerError) throw innerResult;
      anObject$5(innerResult);
      return value;
    };

    var anObject$4 = anObject$g;
    var iteratorClose$1 = iteratorClose$2;

    // call something on iterator step with safe closing on error
    var callWithSafeIterationClosing$1 = function (iterator, fn, value, ENTRIES) {
      try {
        return ENTRIES ? fn(anObject$4(value)[0], value[1]) : fn(value);
      } catch (error) {
        iteratorClose$1(iterator, 'throw', error);
      }
    };

    var DESCRIPTORS$7 = descriptors;
    var definePropertyModule = objectDefineProperty;
    var createPropertyDescriptor = createPropertyDescriptor$5;

    var createProperty$3 = function (object, key, value) {
      if (DESCRIPTORS$7) definePropertyModule.f(object, key, createPropertyDescriptor(0, value));
      else object[key] = value;
    };

    var bind$4 = functionBindContext;
    var call$a = functionCall;
    var toObject$4 = toObject$c;
    var callWithSafeIterationClosing = callWithSafeIterationClosing$1;
    var isArrayIteratorMethod$1 = isArrayIteratorMethod$3;
    var isConstructor$1 = isConstructor$4;
    var lengthOfArrayLike$3 = lengthOfArrayLike$e;
    var createProperty$2 = createProperty$3;
    var getIterator$1 = getIterator$3;
    var getIteratorMethod$1 = getIteratorMethod$4;

    var $Array$1 = Array;

    // `Array.from` method implementation
    // https://tc39.es/ecma262/#sec-array.from
    var arrayFrom = function from(arrayLike /* , mapfn = undefined, thisArg = undefined */) {
      var O = toObject$4(arrayLike);
      var IS_CONSTRUCTOR = isConstructor$1(this);
      var argumentsLength = arguments.length;
      var mapfn = argumentsLength > 1 ? arguments[1] : undefined;
      var mapping = mapfn !== undefined;
      if (mapping) mapfn = bind$4(mapfn, argumentsLength > 2 ? arguments[2] : undefined);
      var iteratorMethod = getIteratorMethod$1(O);
      var index = 0;
      var length, result, step, iterator, next, value;
      // if the target is not iterable or it's an array with the default iterator - use a simple case
      if (iteratorMethod && !(this === $Array$1 && isArrayIteratorMethod$1(iteratorMethod))) {
        result = IS_CONSTRUCTOR ? new this() : [];
        iterator = getIterator$1(O, iteratorMethod);
        next = iterator.next;
        for (;!(step = call$a(next, iterator)).done; index++) {
          value = mapping ? callWithSafeIterationClosing(iterator, mapfn, [step.value, index], true) : step.value;
          createProperty$2(result, index, value);
        }
      } else {
        length = lengthOfArrayLike$3(O);
        result = IS_CONSTRUCTOR ? new this(length) : $Array$1(length);
        for (;length > index; index++) {
          value = mapping ? mapfn(O[index], index) : O[index];
          createProperty$2(result, index, value);
        }
      }
      result.length = index;
      return result;
    };

    var $$t = _export;
    var from = arrayFrom;
    var checkCorrectnessOfIteration$1 = checkCorrectnessOfIteration$3;

    var INCORRECT_ITERATION = !checkCorrectnessOfIteration$1(function (iterable) {
      // eslint-disable-next-line es/no-array-from -- required for testing
      Array.from(iterable);
    });

    // `Array.from` method
    // https://tc39.es/ecma262/#sec-array.from
    $$t({ target: 'Array', stat: true, forced: INCORRECT_ITERATION }, {
      from: from
    });

    var uncurryThis$c = functionUncurryThis;
    var toIntegerOrInfinity$1 = toIntegerOrInfinity$9;
    var toString$8 = toString$c;
    var requireObjectCoercible$4 = requireObjectCoercible$9;

    var charAt$4 = uncurryThis$c(''.charAt);
    var charCodeAt$1 = uncurryThis$c(''.charCodeAt);
    var stringSlice$2 = uncurryThis$c(''.slice);

    var createMethod$1 = function (CONVERT_TO_STRING) {
      return function ($this, pos) {
        var S = toString$8(requireObjectCoercible$4($this));
        var position = toIntegerOrInfinity$1(pos);
        var size = S.length;
        var first, second;
        if (position < 0 || position >= size) return CONVERT_TO_STRING ? '' : undefined;
        first = charCodeAt$1(S, position);
        return first < 0xD800 || first > 0xDBFF || position + 1 === size
          || (second = charCodeAt$1(S, position + 1)) < 0xDC00 || second > 0xDFFF
            ? CONVERT_TO_STRING
              ? charAt$4(S, position)
              : first
            : CONVERT_TO_STRING
              ? stringSlice$2(S, position, position + 2)
              : (first - 0xD800 << 10) + (second - 0xDC00) + 0x10000;
      };
    };

    var stringMultibyte = {
      // `String.prototype.codePointAt` method
      // https://tc39.es/ecma262/#sec-string.prototype.codepointat
      codeAt: createMethod$1(false),
      // `String.prototype.at` method
      // https://github.com/mathiasbynens/String.prototype.at
      charAt: createMethod$1(true)
    };

    var charAt$3 = stringMultibyte.charAt;
    var toString$7 = toString$c;
    var InternalStateModule$1 = internalState;
    var defineIterator = iteratorDefine;
    var createIterResultObject = createIterResultObject$2;

    var STRING_ITERATOR = 'String Iterator';
    var setInternalState$1 = InternalStateModule$1.set;
    var getInternalState$1 = InternalStateModule$1.getterFor(STRING_ITERATOR);

    // `String.prototype[@@iterator]` method
    // https://tc39.es/ecma262/#sec-string.prototype-@@iterator
    defineIterator(String, 'String', function (iterated) {
      setInternalState$1(this, {
        type: STRING_ITERATOR,
        string: toString$7(iterated),
        index: 0
      });
    // `%StringIteratorPrototype%.next` method
    // https://tc39.es/ecma262/#sec-%stringiteratorprototype%.next
    }, function next() {
      var state = getInternalState$1(this);
      var string = state.string;
      var index = state.index;
      var point;
      if (index >= string.length) return createIterResultObject(undefined, true);
      point = charAt$3(string, index);
      state.index += point.length;
      return createIterResultObject(point, false);
    });

    var globalThis$c = globalThis_1;
    var fails$a = fails$C;
    var uncurryThis$b = functionUncurryThis;
    var toString$6 = toString$c;
    var trim = stringTrim.trim;
    var whitespaces = whitespaces$2;

    var $parseInt$1 = globalThis$c.parseInt;
    var Symbol$1 = globalThis$c.Symbol;
    var ITERATOR$1 = Symbol$1 && Symbol$1.iterator;
    var hex = /^[+-]?0x/i;
    var exec$2 = uncurryThis$b(hex.exec);
    var FORCED$2 = $parseInt$1(whitespaces + '08') !== 8 || $parseInt$1(whitespaces + '0x16') !== 22
      // MS Edge 18- broken with boxed symbols
      || (ITERATOR$1 && !fails$a(function () { $parseInt$1(Object(ITERATOR$1)); }));

    // `parseInt` method
    // https://tc39.es/ecma262/#sec-parseint-string-radix
    var numberParseInt = FORCED$2 ? function parseInt(string, radix) {
      var S = trim(toString$6(string));
      return $parseInt$1(S, (radix >>> 0) || (exec$2(hex, S) ? 16 : 10));
    } : $parseInt$1;

    var $$s = _export;
    var parseInt$1 = numberParseInt;

    // `Number.parseInt` method
    // https://tc39.es/ecma262/#sec-number.parseint
    // eslint-disable-next-line es/no-number-parseint -- required for testing
    $$s({ target: 'Number', stat: true, forced: Number.parseInt !== parseInt$1 }, {
      parseInt: parseInt$1
    });

    var $$r = _export;
    var uncurryThis$a = functionUncurryThis;
    var IndexedObject$1 = indexedObject;
    var toIndexedObject$2 = toIndexedObject$a;
    var arrayMethodIsStrict$2 = arrayMethodIsStrict$4;

    var nativeJoin = uncurryThis$a([].join);

    var ES3_STRINGS = IndexedObject$1 !== Object;
    var FORCED$1 = ES3_STRINGS || !arrayMethodIsStrict$2('join', ',');

    // `Array.prototype.join` method
    // https://tc39.es/ecma262/#sec-array.prototype.join
    $$r({ target: 'Array', proto: true, forced: FORCED$1 }, {
      join: function join(separator) {
        return nativeJoin(toIndexedObject$2(this), separator === undefined ? ',' : separator);
      }
    });

    // TODO: Remove from `core-js@4` since it's moved to entry points

    var call$9 = functionCall;
    var defineBuiltIn$3 = defineBuiltIn$b;
    var regexpExec$1 = regexpExec$2;
    var fails$9 = fails$C;
    var wellKnownSymbol$7 = wellKnownSymbol$n;
    var createNonEnumerableProperty$3 = createNonEnumerableProperty$a;

    var SPECIES$3 = wellKnownSymbol$7('species');
    var RegExpPrototype$2 = RegExp.prototype;

    var fixRegexpWellKnownSymbolLogic = function (KEY, exec, FORCED, SHAM) {
      var SYMBOL = wellKnownSymbol$7(KEY);

      var DELEGATES_TO_SYMBOL = !fails$9(function () {
        // String methods call symbol-named RegExp methods
        var O = {};
        O[SYMBOL] = function () { return 7; };
        return ''[KEY](O) !== 7;
      });

      var DELEGATES_TO_EXEC = DELEGATES_TO_SYMBOL && !fails$9(function () {
        // Symbol-named RegExp methods call .exec
        var execCalled = false;
        var re = /a/;

        if (KEY === 'split') {
          // We can't use real regex here since it causes deoptimization
          // and serious performance degradation in V8
          // https://github.com/zloirock/core-js/issues/306
          re = {};
          // RegExp[@@split] doesn't call the regex's exec method, but first creates
          // a new one. We need to return the patched regex when creating the new one.
          re.constructor = {};
          re.constructor[SPECIES$3] = function () { return re; };
          re.flags = '';
          re[SYMBOL] = /./[SYMBOL];
        }

        re.exec = function () {
          execCalled = true;
          return null;
        };

        re[SYMBOL]('');
        return !execCalled;
      });

      if (
        !DELEGATES_TO_SYMBOL ||
        !DELEGATES_TO_EXEC ||
        FORCED
      ) {
        var nativeRegExpMethod = /./[SYMBOL];
        var methods = exec(SYMBOL, ''[KEY], function (nativeMethod, regexp, str, arg2, forceStringMethod) {
          var $exec = regexp.exec;
          if ($exec === regexpExec$1 || $exec === RegExpPrototype$2.exec) {
            if (DELEGATES_TO_SYMBOL && !forceStringMethod) {
              // The native String method already delegates to @@method (this
              // polyfilled function), leasing to infinite recursion.
              // We avoid it by directly calling the native @@method method.
              return { done: true, value: call$9(nativeRegExpMethod, regexp, str, arg2) };
            }
            return { done: true, value: call$9(nativeMethod, str, regexp, arg2) };
          }
          return { done: false };
        });

        defineBuiltIn$3(String.prototype, KEY, methods[0]);
        defineBuiltIn$3(RegExpPrototype$2, SYMBOL, methods[1]);
      }

      if (SHAM) createNonEnumerableProperty$3(RegExpPrototype$2[SYMBOL], 'sham', true);
    };

    var charAt$2 = stringMultibyte.charAt;

    // `AdvanceStringIndex` abstract operation
    // https://tc39.es/ecma262/#sec-advancestringindex
    var advanceStringIndex$1 = function (S, index, unicode) {
      return index + (unicode ? charAt$2(S, index).length : 1);
    };

    var call$8 = functionCall;
    var anObject$3 = anObject$g;
    var isCallable$6 = isCallable$p;
    var classof$4 = classofRaw$2;
    var regexpExec = regexpExec$2;

    var $TypeError$7 = TypeError;

    // `RegExpExec` abstract operation
    // https://tc39.es/ecma262/#sec-regexpexec
    var regexpExecAbstract = function (R, S) {
      var exec = R.exec;
      if (isCallable$6(exec)) {
        var result = call$8(exec, R, S);
        if (result !== null) anObject$3(result);
        return result;
      }
      if (classof$4(R) === 'RegExp') return call$8(regexpExec, R, S);
      throw new $TypeError$7('RegExp#exec called on incompatible receiver');
    };

    var call$7 = functionCall;
    var fixRegExpWellKnownSymbolLogic = fixRegexpWellKnownSymbolLogic;
    var anObject$2 = anObject$g;
    var isNullOrUndefined = isNullOrUndefined$5;
    var toLength$2 = toLength$9;
    var toString$5 = toString$c;
    var requireObjectCoercible$3 = requireObjectCoercible$9;
    var getMethod = getMethod$4;
    var advanceStringIndex = advanceStringIndex$1;
    var regExpExec$1 = regexpExecAbstract;

    // @@match logic
    fixRegExpWellKnownSymbolLogic('match', function (MATCH, nativeMatch, maybeCallNative) {
      return [
        // `String.prototype.match` method
        // https://tc39.es/ecma262/#sec-string.prototype.match
        function match(regexp) {
          var O = requireObjectCoercible$3(this);
          var matcher = isNullOrUndefined(regexp) ? undefined : getMethod(regexp, MATCH);
          return matcher ? call$7(matcher, regexp, O) : new RegExp(regexp)[MATCH](toString$5(O));
        },
        // `RegExp.prototype[@@match]` method
        // https://tc39.es/ecma262/#sec-regexp.prototype-@@match
        function (string) {
          var rx = anObject$2(this);
          var S = toString$5(string);
          var res = maybeCallNative(nativeMatch, rx, S);

          if (res.done) return res.value;

          if (!rx.global) return regExpExec$1(rx, S);

          var fullUnicode = rx.unicode;
          rx.lastIndex = 0;
          var A = [];
          var n = 0;
          var result;
          while ((result = regExpExec$1(rx, S)) !== null) {
            var matchStr = toString$5(result[0]);
            A[n] = matchStr;
            if (matchStr === '') rx.lastIndex = advanceStringIndex(S, toLength$2(rx.lastIndex), fullUnicode);
            n++;
          }
          return n === 0 ? null : A;
        }
      ];
    });

    var DESCRIPTORS$6 = descriptors;
    var FUNCTION_NAME_EXISTS = functionName.EXISTS;
    var uncurryThis$9 = functionUncurryThis;
    var defineBuiltInAccessor$1 = defineBuiltInAccessor$6;

    var FunctionPrototype = Function.prototype;
    var functionToString = uncurryThis$9(FunctionPrototype.toString);
    var nameRE = /function\b(?:\s|\/\*[\S\s]*?\*\/|\/\/[^\n\r]*[\n\r]+)*([^\s(/]*)/;
    var regExpExec = uncurryThis$9(nameRE.exec);
    var NAME = 'name';

    // Function instances `.name` property
    // https://tc39.es/ecma262/#sec-function-instances-name
    if (DESCRIPTORS$6 && !FUNCTION_NAME_EXISTS) {
      defineBuiltInAccessor$1(FunctionPrototype, NAME, {
        configurable: true,
        get: function () {
          try {
            return regExpExec(nameRE, functionToString(this))[1];
          } catch (error) {
            return '';
          }
        }
      });
    }

    var uncurryThis$8 = functionUncurryThis;
    var isArray$2 = isArray$4;
    var isCallable$5 = isCallable$p;
    var classof$3 = classofRaw$2;
    var toString$4 = toString$c;

    var push$1 = uncurryThis$8([].push);

    var getJsonReplacerFunction = function (replacer) {
      if (isCallable$5(replacer)) return replacer;
      if (!isArray$2(replacer)) return;
      var rawLength = replacer.length;
      var keys = [];
      for (var i = 0; i < rawLength; i++) {
        var element = replacer[i];
        if (typeof element == 'string') push$1(keys, element);
        else if (typeof element == 'number' || classof$3(element) === 'Number' || classof$3(element) === 'String') push$1(keys, toString$4(element));
      }
      var keysLength = keys.length;
      var root = true;
      return function (key, value) {
        if (root) {
          root = false;
          return value;
        }
        if (isArray$2(this)) return value;
        for (var j = 0; j < keysLength; j++) if (keys[j] === key) return value;
      };
    };

    var $$q = _export;
    var getBuiltIn$2 = getBuiltIn$8;
    var apply$1 = functionApply;
    var call$6 = functionCall;
    var uncurryThis$7 = functionUncurryThis;
    var fails$8 = fails$C;
    var isCallable$4 = isCallable$p;
    var isSymbol = isSymbol$5;
    var arraySlice$1 = arraySlice$6;
    var getReplacerFunction = getJsonReplacerFunction;
    var NATIVE_SYMBOL = symbolConstructorDetection;

    var $String = String;
    var $stringify = getBuiltIn$2('JSON', 'stringify');
    var exec$1 = uncurryThis$7(/./.exec);
    var charAt$1 = uncurryThis$7(''.charAt);
    var charCodeAt = uncurryThis$7(''.charCodeAt);
    var replace$1 = uncurryThis$7(''.replace);
    var numberToString = uncurryThis$7(1.0.toString);

    var tester = /[\uD800-\uDFFF]/g;
    var low = /^[\uD800-\uDBFF]$/;
    var hi = /^[\uDC00-\uDFFF]$/;

    var WRONG_SYMBOLS_CONVERSION = !NATIVE_SYMBOL || fails$8(function () {
      var symbol = getBuiltIn$2('Symbol')('stringify detection');
      // MS Edge converts symbol values to JSON as {}
      return $stringify([symbol]) !== '[null]'
        // WebKit converts symbol values to JSON as null
        || $stringify({ a: symbol }) !== '{}'
        // V8 throws on boxed symbols
        || $stringify(Object(symbol)) !== '{}';
    });

    // https://github.com/tc39/proposal-well-formed-stringify
    var ILL_FORMED_UNICODE = fails$8(function () {
      return $stringify('\uDF06\uD834') !== '"\\udf06\\ud834"'
        || $stringify('\uDEAD') !== '"\\udead"';
    });

    var stringifyWithSymbolsFix = function (it, replacer) {
      var args = arraySlice$1(arguments);
      var $replacer = getReplacerFunction(replacer);
      if (!isCallable$4($replacer) && (it === undefined || isSymbol(it))) return; // IE8 returns string on undefined
      args[1] = function (key, value) {
        // some old implementations (like WebKit) could pass numbers as keys
        if (isCallable$4($replacer)) value = call$6($replacer, this, $String(key), value);
        if (!isSymbol(value)) return value;
      };
      return apply$1($stringify, null, args);
    };

    var fixIllFormed = function (match, offset, string) {
      var prev = charAt$1(string, offset - 1);
      var next = charAt$1(string, offset + 1);
      if ((exec$1(low, match) && !exec$1(hi, next)) || (exec$1(hi, match) && !exec$1(low, prev))) {
        return '\\u' + numberToString(charCodeAt(match, 0), 16);
      } return match;
    };

    if ($stringify) {
      // `JSON.stringify` method
      // https://tc39.es/ecma262/#sec-json.stringify
      $$q({ target: 'JSON', stat: true, arity: 3, forced: WRONG_SYMBOLS_CONVERSION || ILL_FORMED_UNICODE }, {
        // eslint-disable-next-line no-unused-vars -- required for `.length`
        stringify: function stringify(it, replacer, space) {
          var args = arraySlice$1(arguments);
          var result = apply$1(WRONG_SYMBOLS_CONVERSION ? stringifyWithSymbolsFix : $stringify, null, args);
          return ILL_FORMED_UNICODE && typeof result == 'string' ? replace$1(result, tester, fixIllFormed) : result;
        }
      });
    }

    /* global Bun, Deno -- detection */
    var globalThis$b = globalThis_1;
    var userAgent$3 = environmentUserAgent;
    var classof$2 = classofRaw$2;

    var userAgentStartsWith = function (string) {
      return userAgent$3.slice(0, string.length) === string;
    };

    var environment = (function () {
      if (userAgentStartsWith('Bun/')) return 'BUN';
      if (userAgentStartsWith('Cloudflare-Workers')) return 'CLOUDFLARE';
      if (userAgentStartsWith('Deno/')) return 'DENO';
      if (userAgentStartsWith('Node.js/')) return 'NODE';
      if (globalThis$b.Bun && typeof Bun.version == 'string') return 'BUN';
      if (globalThis$b.Deno && typeof Deno.version == 'object') return 'DENO';
      if (classof$2(globalThis$b.process) === 'process') return 'NODE';
      if (globalThis$b.window && globalThis$b.document) return 'BROWSER';
      return 'REST';
    })();

    var ENVIRONMENT$1 = environment;

    var environmentIsNode = ENVIRONMENT$1 === 'NODE';

    var $TypeError$6 = TypeError;

    var validateArgumentsLength$1 = function (passed, required) {
      if (passed < required) throw new $TypeError$6('Not enough arguments');
      return passed;
    };

    var userAgent$2 = environmentUserAgent;

    // eslint-disable-next-line redos/no-vulnerable -- safe
    var environmentIsIos = /(?:ipad|iphone|ipod).*applewebkit/i.test(userAgent$2);

    var globalThis$a = globalThis_1;
    var apply = functionApply;
    var bind$3 = functionBindContext;
    var isCallable$3 = isCallable$p;
    var hasOwn$1 = hasOwnProperty_1;
    var fails$7 = fails$C;
    var html = html$2;
    var arraySlice = arraySlice$6;
    var createElement = documentCreateElement$2;
    var validateArgumentsLength = validateArgumentsLength$1;
    var IS_IOS$1 = environmentIsIos;
    var IS_NODE$2 = environmentIsNode;

    var set = globalThis$a.setImmediate;
    var clear = globalThis$a.clearImmediate;
    var process$2 = globalThis$a.process;
    var Dispatch = globalThis$a.Dispatch;
    var Function$1 = globalThis$a.Function;
    var MessageChannel = globalThis$a.MessageChannel;
    var String$1 = globalThis$a.String;
    var counter = 0;
    var queue$2 = {};
    var ONREADYSTATECHANGE = 'onreadystatechange';
    var $location, defer, channel, port;

    fails$7(function () {
      // Deno throws a ReferenceError on `location` access without `--location` flag
      $location = globalThis$a.location;
    });

    var run = function (id) {
      if (hasOwn$1(queue$2, id)) {
        var fn = queue$2[id];
        delete queue$2[id];
        fn();
      }
    };

    var runner = function (id) {
      return function () {
        run(id);
      };
    };

    var eventListener = function (event) {
      run(event.data);
    };

    var globalPostMessageDefer = function (id) {
      // old engines have not location.origin
      globalThis$a.postMessage(String$1(id), $location.protocol + '//' + $location.host);
    };

    // Node.js 0.9+ & IE10+ has setImmediate, otherwise:
    if (!set || !clear) {
      set = function setImmediate(handler) {
        validateArgumentsLength(arguments.length, 1);
        var fn = isCallable$3(handler) ? handler : Function$1(handler);
        var args = arraySlice(arguments, 1);
        queue$2[++counter] = function () {
          apply(fn, undefined, args);
        };
        defer(counter);
        return counter;
      };
      clear = function clearImmediate(id) {
        delete queue$2[id];
      };
      // Node.js 0.8-
      if (IS_NODE$2) {
        defer = function (id) {
          process$2.nextTick(runner(id));
        };
      // Sphere (JS game engine) Dispatch API
      } else if (Dispatch && Dispatch.now) {
        defer = function (id) {
          Dispatch.now(runner(id));
        };
      // Browsers with MessageChannel, includes WebWorkers
      // except iOS - https://github.com/zloirock/core-js/issues/624
      } else if (MessageChannel && !IS_IOS$1) {
        channel = new MessageChannel();
        port = channel.port2;
        channel.port1.onmessage = eventListener;
        defer = bind$3(port.postMessage, port);
      // Browsers with postMessage, skip WebWorkers
      // IE8 has postMessage, but it's sync & typeof its postMessage is 'object'
      } else if (
        globalThis$a.addEventListener &&
        isCallable$3(globalThis$a.postMessage) &&
        !globalThis$a.importScripts &&
        $location && $location.protocol !== 'file:' &&
        !fails$7(globalPostMessageDefer)
      ) {
        defer = globalPostMessageDefer;
        globalThis$a.addEventListener('message', eventListener, false);
      // IE8-
      } else if (ONREADYSTATECHANGE in createElement('script')) {
        defer = function (id) {
          html.appendChild(createElement('script'))[ONREADYSTATECHANGE] = function () {
            html.removeChild(this);
            run(id);
          };
        };
      // Rest old browsers
      } else {
        defer = function (id) {
          setTimeout(runner(id), 0);
        };
      }
    }

    var task$1 = {
      set: set,
      clear: clear
    };

    var globalThis$9 = globalThis_1;
    var DESCRIPTORS$5 = descriptors;

    // eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe
    var getOwnPropertyDescriptor$3 = Object.getOwnPropertyDescriptor;

    // Avoid NodeJS experimental warning
    var safeGetBuiltIn$1 = function (name) {
      if (!DESCRIPTORS$5) return globalThis$9[name];
      var descriptor = getOwnPropertyDescriptor$3(globalThis$9, name);
      return descriptor && descriptor.value;
    };

    var Queue$2 = function () {
      this.head = null;
      this.tail = null;
    };

    Queue$2.prototype = {
      add: function (item) {
        var entry = { item: item, next: null };
        var tail = this.tail;
        if (tail) tail.next = entry;
        else this.head = entry;
        this.tail = entry;
      },
      get: function () {
        var entry = this.head;
        if (entry) {
          var next = this.head = entry.next;
          if (next === null) this.tail = null;
          return entry.item;
        }
      }
    };

    var queue$1 = Queue$2;

    var userAgent$1 = environmentUserAgent;

    var environmentIsIosPebble = /ipad|iphone|ipod/i.test(userAgent$1) && typeof Pebble != 'undefined';

    var userAgent = environmentUserAgent;

    var environmentIsWebosWebkit = /web0s(?!.*chrome)/i.test(userAgent);

    var globalThis$8 = globalThis_1;
    var safeGetBuiltIn = safeGetBuiltIn$1;
    var bind$2 = functionBindContext;
    var macrotask = task$1.set;
    var Queue$1 = queue$1;
    var IS_IOS = environmentIsIos;
    var IS_IOS_PEBBLE = environmentIsIosPebble;
    var IS_WEBOS_WEBKIT = environmentIsWebosWebkit;
    var IS_NODE$1 = environmentIsNode;

    var MutationObserver = globalThis$8.MutationObserver || globalThis$8.WebKitMutationObserver;
    var document$2 = globalThis$8.document;
    var process$1 = globalThis$8.process;
    var Promise$1 = globalThis$8.Promise;
    var microtask$1 = safeGetBuiltIn('queueMicrotask');
    var notify$1, toggle, node, promise, then;

    // modern engines have queueMicrotask method
    if (!microtask$1) {
      var queue = new Queue$1();

      var flush = function () {
        var parent, fn;
        if (IS_NODE$1 && (parent = process$1.domain)) parent.exit();
        while (fn = queue.get()) try {
          fn();
        } catch (error) {
          if (queue.head) notify$1();
          throw error;
        }
        if (parent) parent.enter();
      };

      // browsers with MutationObserver, except iOS - https://github.com/zloirock/core-js/issues/339
      // also except WebOS Webkit https://github.com/zloirock/core-js/issues/898
      if (!IS_IOS && !IS_NODE$1 && !IS_WEBOS_WEBKIT && MutationObserver && document$2) {
        toggle = true;
        node = document$2.createTextNode('');
        new MutationObserver(flush).observe(node, { characterData: true });
        notify$1 = function () {
          node.data = toggle = !toggle;
        };
      // environments with maybe non-completely correct, but existent Promise
      } else if (!IS_IOS_PEBBLE && Promise$1 && Promise$1.resolve) {
        // Promise.resolve without an argument throws an error in LG WebOS 2
        promise = Promise$1.resolve(undefined);
        // workaround of WebKit ~ iOS Safari 10.1 bug
        promise.constructor = Promise$1;
        then = bind$2(promise.then, promise);
        notify$1 = function () {
          then(flush);
        };
      // Node.js without promises
      } else if (IS_NODE$1) {
        notify$1 = function () {
          process$1.nextTick(flush);
        };
      // for other environments - macrotask based on:
      // - setImmediate
      // - MessageChannel
      // - window.postMessage
      // - onreadystatechange
      // - setTimeout
      } else {
        // `webpack` dev server bug on IE global methods - use bind(fn, global)
        macrotask = bind$2(macrotask, globalThis$8);
        notify$1 = function () {
          macrotask(flush);
        };
      }

      microtask$1 = function (fn) {
        if (!queue.head) notify$1();
        queue.add(fn);
      };
    }

    var microtask_1 = microtask$1;

    var hostReportErrors$1 = function (a, b) {
      try {
        // eslint-disable-next-line no-console -- safe
        arguments.length === 1 ? console.error(a) : console.error(a, b);
      } catch (error) { /* empty */ }
    };

    var perform$3 = function (exec) {
      try {
        return { error: false, value: exec() };
      } catch (error) {
        return { error: true, value: error };
      }
    };

    var globalThis$7 = globalThis_1;

    var promiseNativeConstructor = globalThis$7.Promise;

    var globalThis$6 = globalThis_1;
    var NativePromiseConstructor$3 = promiseNativeConstructor;
    var isCallable$2 = isCallable$p;
    var isForced$1 = isForced_1;
    var inspectSource = inspectSource$3;
    var wellKnownSymbol$6 = wellKnownSymbol$n;
    var ENVIRONMENT = environment;
    var V8_VERSION$1 = environmentV8Version;

    NativePromiseConstructor$3 && NativePromiseConstructor$3.prototype;
    var SPECIES$2 = wellKnownSymbol$6('species');
    var SUBCLASSING = false;
    var NATIVE_PROMISE_REJECTION_EVENT$1 = isCallable$2(globalThis$6.PromiseRejectionEvent);

    var FORCED_PROMISE_CONSTRUCTOR$5 = isForced$1('Promise', function () {
      var PROMISE_CONSTRUCTOR_SOURCE = inspectSource(NativePromiseConstructor$3);
      var GLOBAL_CORE_JS_PROMISE = PROMISE_CONSTRUCTOR_SOURCE !== String(NativePromiseConstructor$3);
      // V8 6.6 (Node 10 and Chrome 66) have a bug with resolving custom thenables
      // https://bugs.chromium.org/p/chromium/issues/detail?id=830565
      // We can't detect it synchronously, so just check versions
      if (!GLOBAL_CORE_JS_PROMISE && V8_VERSION$1 === 66) return true;
      // We can't use @@species feature detection in V8 since it causes
      // deoptimization and performance degradation
      // https://github.com/zloirock/core-js/issues/679
      if (!V8_VERSION$1 || V8_VERSION$1 < 51 || !/native code/.test(PROMISE_CONSTRUCTOR_SOURCE)) {
        // Detect correctness of subclassing with @@species support
        var promise = new NativePromiseConstructor$3(function (resolve) { resolve(1); });
        var FakePromise = function (exec) {
          exec(function () { /* empty */ }, function () { /* empty */ });
        };
        var constructor = promise.constructor = {};
        constructor[SPECIES$2] = FakePromise;
        SUBCLASSING = promise.then(function () { /* empty */ }) instanceof FakePromise;
        if (!SUBCLASSING) return true;
      // Unhandled rejections tracking support, NodeJS Promise without it fails @@species test
      } return !GLOBAL_CORE_JS_PROMISE && (ENVIRONMENT === 'BROWSER' || ENVIRONMENT === 'DENO') && !NATIVE_PROMISE_REJECTION_EVENT$1;
    });

    var promiseConstructorDetection = {
      CONSTRUCTOR: FORCED_PROMISE_CONSTRUCTOR$5,
      REJECTION_EVENT: NATIVE_PROMISE_REJECTION_EVENT$1,
      SUBCLASSING: SUBCLASSING
    };

    var newPromiseCapability$2 = {};

    var aCallable$3 = aCallable$a;

    var $TypeError$5 = TypeError;

    var PromiseCapability = function (C) {
      var resolve, reject;
      this.promise = new C(function ($$resolve, $$reject) {
        if (resolve !== undefined || reject !== undefined) throw new $TypeError$5('Bad Promise constructor');
        resolve = $$resolve;
        reject = $$reject;
      });
      this.resolve = aCallable$3(resolve);
      this.reject = aCallable$3(reject);
    };

    // `NewPromiseCapability` abstract operation
    // https://tc39.es/ecma262/#sec-newpromisecapability
    newPromiseCapability$2.f = function (C) {
      return new PromiseCapability(C);
    };

    var $$p = _export;
    var IS_NODE = environmentIsNode;
    var globalThis$5 = globalThis_1;
    var call$5 = functionCall;
    var defineBuiltIn$2 = defineBuiltIn$b;
    var setPrototypeOf = objectSetPrototypeOf;
    var setToStringTag$1 = setToStringTag$5;
    var setSpecies$2 = setSpecies$4;
    var aCallable$2 = aCallable$a;
    var isCallable$1 = isCallable$p;
    var isObject$3 = isObject$h;
    var anInstance = anInstance$3;
    var speciesConstructor = speciesConstructor$3;
    var task = task$1.set;
    var microtask = microtask_1;
    var hostReportErrors = hostReportErrors$1;
    var perform$2 = perform$3;
    var Queue = queue$1;
    var InternalStateModule = internalState;
    var NativePromiseConstructor$2 = promiseNativeConstructor;
    var PromiseConstructorDetection = promiseConstructorDetection;
    var newPromiseCapabilityModule$3 = newPromiseCapability$2;

    var PROMISE = 'Promise';
    var FORCED_PROMISE_CONSTRUCTOR$4 = PromiseConstructorDetection.CONSTRUCTOR;
    var NATIVE_PROMISE_REJECTION_EVENT = PromiseConstructorDetection.REJECTION_EVENT;
    var NATIVE_PROMISE_SUBCLASSING = PromiseConstructorDetection.SUBCLASSING;
    var getInternalPromiseState = InternalStateModule.getterFor(PROMISE);
    var setInternalState = InternalStateModule.set;
    var NativePromisePrototype$1 = NativePromiseConstructor$2 && NativePromiseConstructor$2.prototype;
    var PromiseConstructor = NativePromiseConstructor$2;
    var PromisePrototype = NativePromisePrototype$1;
    var TypeError$1 = globalThis$5.TypeError;
    var document$1 = globalThis$5.document;
    var process = globalThis$5.process;
    var newPromiseCapability$1 = newPromiseCapabilityModule$3.f;
    var newGenericPromiseCapability = newPromiseCapability$1;

    var DISPATCH_EVENT = !!(document$1 && document$1.createEvent && globalThis$5.dispatchEvent);
    var UNHANDLED_REJECTION = 'unhandledrejection';
    var REJECTION_HANDLED = 'rejectionhandled';
    var PENDING = 0;
    var FULFILLED = 1;
    var REJECTED = 2;
    var HANDLED = 1;
    var UNHANDLED = 2;

    var Internal, OwnPromiseCapability, PromiseWrapper, nativeThen;

    // helpers
    var isThenable = function (it) {
      var then;
      return isObject$3(it) && isCallable$1(then = it.then) ? then : false;
    };

    var callReaction = function (reaction, state) {
      var value = state.value;
      var ok = state.state === FULFILLED;
      var handler = ok ? reaction.ok : reaction.fail;
      var resolve = reaction.resolve;
      var reject = reaction.reject;
      var domain = reaction.domain;
      var result, then, exited;
      try {
        if (handler) {
          if (!ok) {
            if (state.rejection === UNHANDLED) onHandleUnhandled(state);
            state.rejection = HANDLED;
          }
          if (handler === true) result = value;
          else {
            if (domain) domain.enter();
            result = handler(value); // can throw
            if (domain) {
              domain.exit();
              exited = true;
            }
          }
          if (result === reaction.promise) {
            reject(new TypeError$1('Promise-chain cycle'));
          } else if (then = isThenable(result)) {
            call$5(then, result, resolve, reject);
          } else resolve(result);
        } else reject(value);
      } catch (error) {
        if (domain && !exited) domain.exit();
        reject(error);
      }
    };

    var notify = function (state, isReject) {
      if (state.notified) return;
      state.notified = true;
      microtask(function () {
        var reactions = state.reactions;
        var reaction;
        while (reaction = reactions.get()) {
          callReaction(reaction, state);
        }
        state.notified = false;
        if (isReject && !state.rejection) onUnhandled(state);
      });
    };

    var dispatchEvent = function (name, promise, reason) {
      var event, handler;
      if (DISPATCH_EVENT) {
        event = document$1.createEvent('Event');
        event.promise = promise;
        event.reason = reason;
        event.initEvent(name, false, true);
        globalThis$5.dispatchEvent(event);
      } else event = { promise: promise, reason: reason };
      if (!NATIVE_PROMISE_REJECTION_EVENT && (handler = globalThis$5['on' + name])) handler(event);
      else if (name === UNHANDLED_REJECTION) hostReportErrors('Unhandled promise rejection', reason);
    };

    var onUnhandled = function (state) {
      call$5(task, globalThis$5, function () {
        var promise = state.facade;
        var value = state.value;
        var IS_UNHANDLED = isUnhandled(state);
        var result;
        if (IS_UNHANDLED) {
          result = perform$2(function () {
            if (IS_NODE) {
              process.emit('unhandledRejection', value, promise);
            } else dispatchEvent(UNHANDLED_REJECTION, promise, value);
          });
          // Browsers should not trigger `rejectionHandled` event if it was handled here, NodeJS - should
          state.rejection = IS_NODE || isUnhandled(state) ? UNHANDLED : HANDLED;
          if (result.error) throw result.value;
        }
      });
    };

    var isUnhandled = function (state) {
      return state.rejection !== HANDLED && !state.parent;
    };

    var onHandleUnhandled = function (state) {
      call$5(task, globalThis$5, function () {
        var promise = state.facade;
        if (IS_NODE) {
          process.emit('rejectionHandled', promise);
        } else dispatchEvent(REJECTION_HANDLED, promise, state.value);
      });
    };

    var bind$1 = function (fn, state, unwrap) {
      return function (value) {
        fn(state, value, unwrap);
      };
    };

    var internalReject = function (state, value, unwrap) {
      if (state.done) return;
      state.done = true;
      if (unwrap) state = unwrap;
      state.value = value;
      state.state = REJECTED;
      notify(state, true);
    };

    var internalResolve = function (state, value, unwrap) {
      if (state.done) return;
      state.done = true;
      if (unwrap) state = unwrap;
      try {
        if (state.facade === value) throw new TypeError$1("Promise can't be resolved itself");
        var then = isThenable(value);
        if (then) {
          microtask(function () {
            var wrapper = { done: false };
            try {
              call$5(then, value,
                bind$1(internalResolve, wrapper, state),
                bind$1(internalReject, wrapper, state)
              );
            } catch (error) {
              internalReject(wrapper, error, state);
            }
          });
        } else {
          state.value = value;
          state.state = FULFILLED;
          notify(state, false);
        }
      } catch (error) {
        internalReject({ done: false }, error, state);
      }
    };

    // constructor polyfill
    if (FORCED_PROMISE_CONSTRUCTOR$4) {
      // 25.4.3.1 Promise(executor)
      PromiseConstructor = function Promise(executor) {
        anInstance(this, PromisePrototype);
        aCallable$2(executor);
        call$5(Internal, this);
        var state = getInternalPromiseState(this);
        try {
          executor(bind$1(internalResolve, state), bind$1(internalReject, state));
        } catch (error) {
          internalReject(state, error);
        }
      };

      PromisePrototype = PromiseConstructor.prototype;

      // eslint-disable-next-line no-unused-vars -- required for `.length`
      Internal = function Promise(executor) {
        setInternalState(this, {
          type: PROMISE,
          done: false,
          notified: false,
          parent: false,
          reactions: new Queue(),
          rejection: false,
          state: PENDING,
          value: null
        });
      };

      // `Promise.prototype.then` method
      // https://tc39.es/ecma262/#sec-promise.prototype.then
      Internal.prototype = defineBuiltIn$2(PromisePrototype, 'then', function then(onFulfilled, onRejected) {
        var state = getInternalPromiseState(this);
        var reaction = newPromiseCapability$1(speciesConstructor(this, PromiseConstructor));
        state.parent = true;
        reaction.ok = isCallable$1(onFulfilled) ? onFulfilled : true;
        reaction.fail = isCallable$1(onRejected) && onRejected;
        reaction.domain = IS_NODE ? process.domain : undefined;
        if (state.state === PENDING) state.reactions.add(reaction);
        else microtask(function () {
          callReaction(reaction, state);
        });
        return reaction.promise;
      });

      OwnPromiseCapability = function () {
        var promise = new Internal();
        var state = getInternalPromiseState(promise);
        this.promise = promise;
        this.resolve = bind$1(internalResolve, state);
        this.reject = bind$1(internalReject, state);
      };

      newPromiseCapabilityModule$3.f = newPromiseCapability$1 = function (C) {
        return C === PromiseConstructor || C === PromiseWrapper
          ? new OwnPromiseCapability(C)
          : newGenericPromiseCapability(C);
      };

      if (isCallable$1(NativePromiseConstructor$2) && NativePromisePrototype$1 !== Object.prototype) {
        nativeThen = NativePromisePrototype$1.then;

        if (!NATIVE_PROMISE_SUBCLASSING) {
          // make `Promise#then` return a polyfilled `Promise` for native promise-based APIs
          defineBuiltIn$2(NativePromisePrototype$1, 'then', function then(onFulfilled, onRejected) {
            var that = this;
            return new PromiseConstructor(function (resolve, reject) {
              call$5(nativeThen, that, resolve, reject);
            }).then(onFulfilled, onRejected);
          // https://github.com/zloirock/core-js/issues/640
          }, { unsafe: true });
        }

        // make `.constructor === Promise` work for native promise-based APIs
        try {
          delete NativePromisePrototype$1.constructor;
        } catch (error) { /* empty */ }

        // make `instanceof Promise` work for native promise-based APIs
        if (setPrototypeOf) {
          setPrototypeOf(NativePromisePrototype$1, PromisePrototype);
        }
      }
    }

    $$p({ global: true, constructor: true, wrap: true, forced: FORCED_PROMISE_CONSTRUCTOR$4 }, {
      Promise: PromiseConstructor
    });

    setToStringTag$1(PromiseConstructor, PROMISE, false);
    setSpecies$2(PROMISE);

    var bind = functionBindContext;
    var call$4 = functionCall;
    var anObject$1 = anObject$g;
    var tryToString = tryToString$6;
    var isArrayIteratorMethod = isArrayIteratorMethod$3;
    var lengthOfArrayLike$2 = lengthOfArrayLike$e;
    var isPrototypeOf$1 = objectIsPrototypeOf;
    var getIterator = getIterator$3;
    var getIteratorMethod = getIteratorMethod$4;
    var iteratorClose = iteratorClose$2;

    var $TypeError$4 = TypeError;

    var Result = function (stopped, result) {
      this.stopped = stopped;
      this.result = result;
    };

    var ResultPrototype = Result.prototype;

    var iterate$2 = function (iterable, unboundFunction, options) {
      var that = options && options.that;
      var AS_ENTRIES = !!(options && options.AS_ENTRIES);
      var IS_RECORD = !!(options && options.IS_RECORD);
      var IS_ITERATOR = !!(options && options.IS_ITERATOR);
      var INTERRUPTED = !!(options && options.INTERRUPTED);
      var fn = bind(unboundFunction, that);
      var iterator, iterFn, index, length, result, next, step;

      var stop = function (condition) {
        if (iterator) iteratorClose(iterator, 'normal', condition);
        return new Result(true, condition);
      };

      var callFn = function (value) {
        if (AS_ENTRIES) {
          anObject$1(value);
          return INTERRUPTED ? fn(value[0], value[1], stop) : fn(value[0], value[1]);
        } return INTERRUPTED ? fn(value, stop) : fn(value);
      };

      if (IS_RECORD) {
        iterator = iterable.iterator;
      } else if (IS_ITERATOR) {
        iterator = iterable;
      } else {
        iterFn = getIteratorMethod(iterable);
        if (!iterFn) throw new $TypeError$4(tryToString(iterable) + ' is not iterable');
        // optimisation for array iterators
        if (isArrayIteratorMethod(iterFn)) {
          for (index = 0, length = lengthOfArrayLike$2(iterable); length > index; index++) {
            result = callFn(iterable[index]);
            if (result && isPrototypeOf$1(ResultPrototype, result)) return result;
          } return new Result(false);
        }
        iterator = getIterator(iterable, iterFn);
      }

      next = IS_RECORD ? iterable.next : iterator.next;
      while (!(step = call$4(next, iterator)).done) {
        try {
          result = callFn(step.value);
        } catch (error) {
          iteratorClose(iterator, 'throw', error);
        }
        if (typeof result == 'object' && result && isPrototypeOf$1(ResultPrototype, result)) return result;
      } return new Result(false);
    };

    var NativePromiseConstructor$1 = promiseNativeConstructor;
    var checkCorrectnessOfIteration = checkCorrectnessOfIteration$3;
    var FORCED_PROMISE_CONSTRUCTOR$3 = promiseConstructorDetection.CONSTRUCTOR;

    var promiseStaticsIncorrectIteration = FORCED_PROMISE_CONSTRUCTOR$3 || !checkCorrectnessOfIteration(function (iterable) {
      NativePromiseConstructor$1.all(iterable).then(undefined, function () { /* empty */ });
    });

    var $$o = _export;
    var call$3 = functionCall;
    var aCallable$1 = aCallable$a;
    var newPromiseCapabilityModule$2 = newPromiseCapability$2;
    var perform$1 = perform$3;
    var iterate$1 = iterate$2;
    var PROMISE_STATICS_INCORRECT_ITERATION$1 = promiseStaticsIncorrectIteration;

    // `Promise.all` method
    // https://tc39.es/ecma262/#sec-promise.all
    $$o({ target: 'Promise', stat: true, forced: PROMISE_STATICS_INCORRECT_ITERATION$1 }, {
      all: function all(iterable) {
        var C = this;
        var capability = newPromiseCapabilityModule$2.f(C);
        var resolve = capability.resolve;
        var reject = capability.reject;
        var result = perform$1(function () {
          var $promiseResolve = aCallable$1(C.resolve);
          var values = [];
          var counter = 0;
          var remaining = 1;
          iterate$1(iterable, function (promise) {
            var index = counter++;
            var alreadyCalled = false;
            remaining++;
            call$3($promiseResolve, C, promise).then(function (value) {
              if (alreadyCalled) return;
              alreadyCalled = true;
              values[index] = value;
              --remaining || resolve(values);
            }, reject);
          });
          --remaining || resolve(values);
        });
        if (result.error) reject(result.value);
        return capability.promise;
      }
    });

    var $$n = _export;
    var FORCED_PROMISE_CONSTRUCTOR$2 = promiseConstructorDetection.CONSTRUCTOR;
    var NativePromiseConstructor = promiseNativeConstructor;
    var getBuiltIn$1 = getBuiltIn$8;
    var isCallable = isCallable$p;
    var defineBuiltIn$1 = defineBuiltIn$b;

    var NativePromisePrototype = NativePromiseConstructor && NativePromiseConstructor.prototype;

    // `Promise.prototype.catch` method
    // https://tc39.es/ecma262/#sec-promise.prototype.catch
    $$n({ target: 'Promise', proto: true, forced: FORCED_PROMISE_CONSTRUCTOR$2, real: true }, {
      'catch': function (onRejected) {
        return this.then(undefined, onRejected);
      }
    });

    // makes sure that native promise-based APIs `Promise#catch` properly works with patched `Promise#then`
    if (isCallable(NativePromiseConstructor)) {
      var method = getBuiltIn$1('Promise').prototype['catch'];
      if (NativePromisePrototype['catch'] !== method) {
        defineBuiltIn$1(NativePromisePrototype, 'catch', method, { unsafe: true });
      }
    }

    var $$m = _export;
    var call$2 = functionCall;
    var aCallable = aCallable$a;
    var newPromiseCapabilityModule$1 = newPromiseCapability$2;
    var perform = perform$3;
    var iterate = iterate$2;
    var PROMISE_STATICS_INCORRECT_ITERATION = promiseStaticsIncorrectIteration;

    // `Promise.race` method
    // https://tc39.es/ecma262/#sec-promise.race
    $$m({ target: 'Promise', stat: true, forced: PROMISE_STATICS_INCORRECT_ITERATION }, {
      race: function race(iterable) {
        var C = this;
        var capability = newPromiseCapabilityModule$1.f(C);
        var reject = capability.reject;
        var result = perform(function () {
          var $promiseResolve = aCallable(C.resolve);
          iterate(iterable, function (promise) {
            call$2($promiseResolve, C, promise).then(capability.resolve, reject);
          });
        });
        if (result.error) reject(result.value);
        return capability.promise;
      }
    });

    var $$l = _export;
    var newPromiseCapabilityModule = newPromiseCapability$2;
    var FORCED_PROMISE_CONSTRUCTOR$1 = promiseConstructorDetection.CONSTRUCTOR;

    // `Promise.reject` method
    // https://tc39.es/ecma262/#sec-promise.reject
    $$l({ target: 'Promise', stat: true, forced: FORCED_PROMISE_CONSTRUCTOR$1 }, {
      reject: function reject(r) {
        var capability = newPromiseCapabilityModule.f(this);
        var capabilityReject = capability.reject;
        capabilityReject(r);
        return capability.promise;
      }
    });

    var anObject = anObject$g;
    var isObject$2 = isObject$h;
    var newPromiseCapability = newPromiseCapability$2;

    var promiseResolve$1 = function (C, x) {
      anObject(C);
      if (isObject$2(x) && x.constructor === C) return x;
      var promiseCapability = newPromiseCapability.f(C);
      var resolve = promiseCapability.resolve;
      resolve(x);
      return promiseCapability.promise;
    };

    var $$k = _export;
    var getBuiltIn = getBuiltIn$8;
    var FORCED_PROMISE_CONSTRUCTOR = promiseConstructorDetection.CONSTRUCTOR;
    var promiseResolve = promiseResolve$1;

    getBuiltIn('Promise');

    // `Promise.resolve` method
    // https://tc39.es/ecma262/#sec-promise.resolve
    $$k({ target: 'Promise', stat: true, forced: FORCED_PROMISE_CONSTRUCTOR }, {
      resolve: function resolve(x) {
        return promiseResolve(this, x);
      }
    });

    var isObject$1 = isObject$h;
    var classof$1 = classofRaw$2;
    var wellKnownSymbol$5 = wellKnownSymbol$n;

    var MATCH$2 = wellKnownSymbol$5('match');

    // `IsRegExp` abstract operation
    // https://tc39.es/ecma262/#sec-isregexp
    var isRegexp = function (it) {
      var isRegExp;
      return isObject$1(it) && ((isRegExp = it[MATCH$2]) !== undefined ? !!isRegExp : classof$1(it) === 'RegExp');
    };

    var defineProperty$1 = objectDefineProperty.f;

    var proxyAccessor$1 = function (Target, Source, key) {
      key in Target || defineProperty$1(Target, key, {
        configurable: true,
        get: function () { return Source[key]; },
        set: function (it) { Source[key] = it; }
      });
    };

    var DESCRIPTORS$4 = descriptors;
    var globalThis$4 = globalThis_1;
    var uncurryThis$6 = functionUncurryThis;
    var isForced = isForced_1;
    var inheritIfRequired = inheritIfRequired$4;
    var createNonEnumerableProperty$2 = createNonEnumerableProperty$a;
    var create = objectCreate;
    var getOwnPropertyNames = objectGetOwnPropertyNames.f;
    var isPrototypeOf = objectIsPrototypeOf;
    var isRegExp$1 = isRegexp;
    var toString$3 = toString$c;
    var getRegExpFlags = regexpGetFlags;
    var stickyHelpers = regexpStickyHelpers;
    var proxyAccessor = proxyAccessor$1;
    var defineBuiltIn = defineBuiltIn$b;
    var fails$6 = fails$C;
    var hasOwn = hasOwnProperty_1;
    var enforceInternalState = internalState.enforce;
    var setSpecies$1 = setSpecies$4;
    var wellKnownSymbol$4 = wellKnownSymbol$n;
    var UNSUPPORTED_DOT_ALL = regexpUnsupportedDotAll;
    var UNSUPPORTED_NCG = regexpUnsupportedNcg;

    var MATCH$1 = wellKnownSymbol$4('match');
    var NativeRegExp = globalThis$4.RegExp;
    var RegExpPrototype$1 = NativeRegExp.prototype;
    var SyntaxError = globalThis$4.SyntaxError;
    var exec = uncurryThis$6(RegExpPrototype$1.exec);
    var charAt = uncurryThis$6(''.charAt);
    var replace = uncurryThis$6(''.replace);
    var stringIndexOf$1 = uncurryThis$6(''.indexOf);
    var stringSlice$1 = uncurryThis$6(''.slice);
    // TODO: Use only proper RegExpIdentifierName
    var IS_NCG = /^\?<[^\s\d!#%&*+<=>@^][^\s!#%&*+<=>@^]*>/;
    var re1 = /a/g;
    var re2 = /a/g;

    // "new" should create a new object, old webkit bug
    var CORRECT_NEW = new NativeRegExp(re1) !== re1;

    var MISSED_STICKY$1 = stickyHelpers.MISSED_STICKY;
    var UNSUPPORTED_Y = stickyHelpers.UNSUPPORTED_Y;

    var BASE_FORCED = DESCRIPTORS$4 &&
      (!CORRECT_NEW || MISSED_STICKY$1 || UNSUPPORTED_DOT_ALL || UNSUPPORTED_NCG || fails$6(function () {
        re2[MATCH$1] = false;
        // RegExp constructor can alter flags and IsRegExp works correct with @@match
        // eslint-disable-next-line sonar/inconsistent-function-call -- required for testing
        return NativeRegExp(re1) !== re1 || NativeRegExp(re2) === re2 || String(NativeRegExp(re1, 'i')) !== '/a/i';
      }));

    var handleDotAll = function (string) {
      var length = string.length;
      var index = 0;
      var result = '';
      var brackets = false;
      var chr;
      for (; index <= length; index++) {
        chr = charAt(string, index);
        if (chr === '\\') {
          result += chr + charAt(string, ++index);
          continue;
        }
        if (!brackets && chr === '.') {
          result += '[\\s\\S]';
        } else {
          if (chr === '[') {
            brackets = true;
          } else if (chr === ']') {
            brackets = false;
          } result += chr;
        }
      } return result;
    };

    var handleNCG = function (string) {
      var length = string.length;
      var index = 0;
      var result = '';
      var named = [];
      var names = create(null);
      var brackets = false;
      var ncg = false;
      var groupid = 0;
      var groupname = '';
      var chr;
      for (; index <= length; index++) {
        chr = charAt(string, index);
        if (chr === '\\') {
          chr += charAt(string, ++index);
        } else if (chr === ']') {
          brackets = false;
        } else if (!brackets) switch (true) {
          case chr === '[':
            brackets = true;
            break;
          case chr === '(':
            result += chr;
            // ignore non-capturing groups
            if (stringSlice$1(string, index + 1, index + 3) === '?:') {
              continue;
            }
            if (exec(IS_NCG, stringSlice$1(string, index + 1))) {
              index += 2;
              ncg = true;
            }
            groupid++;
            continue;
          case chr === '>' && ncg:
            if (groupname === '' || hasOwn(names, groupname)) {
              throw new SyntaxError('Invalid capture group name');
            }
            names[groupname] = true;
            named[named.length] = [groupname, groupid];
            ncg = false;
            groupname = '';
            continue;
        }
        if (ncg) groupname += chr;
        else result += chr;
      } return [result, named];
    };

    // `RegExp` constructor
    // https://tc39.es/ecma262/#sec-regexp-constructor
    if (isForced('RegExp', BASE_FORCED)) {
      var RegExpWrapper = function RegExp(pattern, flags) {
        var thisIsRegExp = isPrototypeOf(RegExpPrototype$1, this);
        var patternIsRegExp = isRegExp$1(pattern);
        var flagsAreUndefined = flags === undefined;
        var groups = [];
        var rawPattern = pattern;
        var rawFlags, dotAll, sticky, handled, result, state;

        if (!thisIsRegExp && patternIsRegExp && flagsAreUndefined && pattern.constructor === RegExpWrapper) {
          return pattern;
        }

        if (patternIsRegExp || isPrototypeOf(RegExpPrototype$1, pattern)) {
          pattern = pattern.source;
          if (flagsAreUndefined) flags = getRegExpFlags(rawPattern);
        }

        pattern = pattern === undefined ? '' : toString$3(pattern);
        flags = flags === undefined ? '' : toString$3(flags);
        rawPattern = pattern;

        if (UNSUPPORTED_DOT_ALL && 'dotAll' in re1) {
          dotAll = !!flags && stringIndexOf$1(flags, 's') > -1;
          if (dotAll) flags = replace(flags, /s/g, '');
        }

        rawFlags = flags;

        if (MISSED_STICKY$1 && 'sticky' in re1) {
          sticky = !!flags && stringIndexOf$1(flags, 'y') > -1;
          if (sticky && UNSUPPORTED_Y) flags = replace(flags, /y/g, '');
        }

        if (UNSUPPORTED_NCG) {
          handled = handleNCG(pattern);
          pattern = handled[0];
          groups = handled[1];
        }

        result = inheritIfRequired(NativeRegExp(pattern, flags), thisIsRegExp ? this : RegExpPrototype$1, RegExpWrapper);

        if (dotAll || sticky || groups.length) {
          state = enforceInternalState(result);
          if (dotAll) {
            state.dotAll = true;
            state.raw = RegExpWrapper(handleDotAll(pattern), rawFlags);
          }
          if (sticky) state.sticky = true;
          if (groups.length) state.groups = groups;
        }

        if (pattern !== rawPattern) try {
          // fails in old engines, but we have no alternatives for unsupported regex syntax
          createNonEnumerableProperty$2(result, 'source', rawPattern === '' ? '(?:)' : rawPattern);
        } catch (error) { /* empty */ }

        return result;
      };

      for (var keys = getOwnPropertyNames(NativeRegExp), index = 0; keys.length > index;) {
        proxyAccessor(RegExpWrapper, NativeRegExp, keys[index++]);
      }

      RegExpPrototype$1.constructor = RegExpWrapper;
      RegExpWrapper.prototype = RegExpPrototype$1;
      defineBuiltIn(globalThis$4, 'RegExp', RegExpWrapper, { constructor: true });
    }

    // https://tc39.es/ecma262/#sec-get-regexp-@@species
    setSpecies$1('RegExp');

    var DESCRIPTORS$3 = descriptors;
    var MISSED_STICKY = regexpStickyHelpers.MISSED_STICKY;
    var classof = classofRaw$2;
    var defineBuiltInAccessor = defineBuiltInAccessor$6;
    var getInternalState = internalState.get;

    var RegExpPrototype = RegExp.prototype;
    var $TypeError$3 = TypeError;

    // `RegExp.prototype.sticky` getter
    // https://tc39.es/ecma262/#sec-get-regexp.prototype.sticky
    if (DESCRIPTORS$3 && MISSED_STICKY) {
      defineBuiltInAccessor(RegExpPrototype, 'sticky', {
        configurable: true,
        get: function sticky() {
          if (this === RegExpPrototype) return;
          // We can't use InternalStateModule.getterFor because
          // we don't add metadata for regexps created by a literal.
          if (classof(this) === 'RegExp') {
            return !!getInternalState(this).sticky;
          }
          throw new $TypeError$3('Incompatible receiver, RegExp required');
        }
      });
    }

    // iterable DOM collections
    // flag - `iterable` interface - 'entries', 'keys', 'values', 'forEach' methods
    var domIterables = {
      CSSRuleList: 0,
      CSSStyleDeclaration: 0,
      CSSValueList: 0,
      ClientRectList: 0,
      DOMRectList: 0,
      DOMStringList: 0,
      DOMTokenList: 1,
      DataTransferItemList: 0,
      FileList: 0,
      HTMLAllCollection: 0,
      HTMLCollection: 0,
      HTMLFormElement: 0,
      HTMLSelectElement: 0,
      MediaList: 0,
      MimeTypeArray: 0,
      NamedNodeMap: 0,
      NodeList: 1,
      PaintRequestList: 0,
      Plugin: 0,
      PluginArray: 0,
      SVGLengthList: 0,
      SVGNumberList: 0,
      SVGPathSegList: 0,
      SVGPointList: 0,
      SVGStringList: 0,
      SVGTransformList: 0,
      SourceBufferList: 0,
      StyleSheetList: 0,
      TextTrackCueList: 0,
      TextTrackList: 0,
      TouchList: 0
    };

    // in old WebKit versions, `element.classList` is not an instance of global `DOMTokenList`
    var documentCreateElement = documentCreateElement$2;

    var classList = documentCreateElement('span').classList;
    var DOMTokenListPrototype$2 = classList && classList.constructor && classList.constructor.prototype;

    var domTokenListPrototype = DOMTokenListPrototype$2 === Object.prototype ? undefined : DOMTokenListPrototype$2;

    var $forEach = arrayIteration.forEach;
    var arrayMethodIsStrict$1 = arrayMethodIsStrict$4;

    var STRICT_METHOD = arrayMethodIsStrict$1('forEach');

    // `Array.prototype.forEach` method implementation
    // https://tc39.es/ecma262/#sec-array.prototype.foreach
    var arrayForEach = !STRICT_METHOD ? function forEach(callbackfn /* , thisArg */) {
      return $forEach(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined);
    // eslint-disable-next-line es/no-array-prototype-foreach -- safe
    } : [].forEach;

    var globalThis$3 = globalThis_1;
    var DOMIterables$1 = domIterables;
    var DOMTokenListPrototype$1 = domTokenListPrototype;
    var forEach = arrayForEach;
    var createNonEnumerableProperty$1 = createNonEnumerableProperty$a;

    var handlePrototype$1 = function (CollectionPrototype) {
      // some Chrome versions have non-configurable methods on DOMTokenList
      if (CollectionPrototype && CollectionPrototype.forEach !== forEach) try {
        createNonEnumerableProperty$1(CollectionPrototype, 'forEach', forEach);
      } catch (error) {
        CollectionPrototype.forEach = forEach;
      }
    };

    for (var COLLECTION_NAME$1 in DOMIterables$1) {
      if (DOMIterables$1[COLLECTION_NAME$1]) {
        handlePrototype$1(globalThis$3[COLLECTION_NAME$1] && globalThis$3[COLLECTION_NAME$1].prototype);
      }
    }

    handlePrototype$1(DOMTokenListPrototype$1);

    var fails$5 = fails$C;
    var wellKnownSymbol$3 = wellKnownSymbol$n;
    var V8_VERSION = environmentV8Version;

    var SPECIES$1 = wellKnownSymbol$3('species');

    var arrayMethodHasSpeciesSupport$4 = function (METHOD_NAME) {
      // We can't use this feature detection in V8 since it causes
      // deoptimization and serious performance degradation
      // https://github.com/zloirock/core-js/issues/677
      return V8_VERSION >= 51 || !fails$5(function () {
        var array = [];
        var constructor = array.constructor = {};
        constructor[SPECIES$1] = function () {
          return { foo: 1 };
        };
        return array[METHOD_NAME](Boolean).foo !== 1;
      });
    };

    var $$j = _export;
    var $filter = arrayIteration.filter;
    var arrayMethodHasSpeciesSupport$3 = arrayMethodHasSpeciesSupport$4;

    var HAS_SPECIES_SUPPORT$3 = arrayMethodHasSpeciesSupport$3('filter');

    // `Array.prototype.filter` method
    // https://tc39.es/ecma262/#sec-array.prototype.filter
    // with adding support of @@species
    $$j({ target: 'Array', proto: true, forced: !HAS_SPECIES_SUPPORT$3 }, {
      filter: function filter(callbackfn /* , thisArg */) {
        return $filter(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined);
      }
    });

    var $$i = _export;
    var toObject$3 = toObject$c;
    var nativeKeys = objectKeys$3;
    var fails$4 = fails$C;

    var FAILS_ON_PRIMITIVES$1 = fails$4(function () { nativeKeys(1); });

    // `Object.keys` method
    // https://tc39.es/ecma262/#sec-object.keys
    $$i({ target: 'Object', stat: true, forced: FAILS_ON_PRIMITIVES$1 }, {
      keys: function keys(it) {
        return nativeKeys(toObject$3(it));
      }
    });

    var $$h = _export;
    var $findIndex = arrayIteration.findIndex;
    var addToUnscopables$2 = addToUnscopables$4;

    var FIND_INDEX = 'findIndex';
    var SKIPS_HOLES$1 = true;

    // Shouldn't skip holes
    // eslint-disable-next-line es/no-array-prototype-findindex -- testing
    if (FIND_INDEX in []) Array(1)[FIND_INDEX](function () { SKIPS_HOLES$1 = false; });

    // `Array.prototype.findIndex` method
    // https://tc39.es/ecma262/#sec-array.prototype.findindex
    $$h({ target: 'Array', proto: true, forced: SKIPS_HOLES$1 }, {
      findIndex: function findIndex(callbackfn /* , that = undefined */) {
        return $findIndex(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined);
      }
    });

    // https://tc39.es/ecma262/#sec-array.prototype-@@unscopables
    addToUnscopables$2(FIND_INDEX);

    var DESCRIPTORS$2 = descriptors;
    var isArray$1 = isArray$4;

    var $TypeError$2 = TypeError;
    // eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe
    var getOwnPropertyDescriptor$2 = Object.getOwnPropertyDescriptor;

    // Safari < 13 does not throw an error in this case
    var SILENT_ON_NON_WRITABLE_LENGTH_SET = DESCRIPTORS$2 && !function () {
      // makes no sense without proper strict mode support
      if (this !== undefined) return true;
      try {
        // eslint-disable-next-line es/no-object-defineproperty -- safe
        Object.defineProperty([], 'length', { writable: false }).length = 1;
      } catch (error) {
        return error instanceof TypeError;
      }
    }();

    var arraySetLength = SILENT_ON_NON_WRITABLE_LENGTH_SET ? function (O, length) {
      if (isArray$1(O) && !getOwnPropertyDescriptor$2(O, 'length').writable) {
        throw new $TypeError$2('Cannot set read only .length');
      } return O.length = length;
    } : function (O, length) {
      return O.length = length;
    };

    var $TypeError$1 = TypeError;
    var MAX_SAFE_INTEGER = 0x1FFFFFFFFFFFFF; // 2 ** 53 - 1 == 9007199254740991

    var doesNotExceedSafeInteger$1 = function (it) {
      if (it > MAX_SAFE_INTEGER) throw $TypeError$1('Maximum allowed index exceeded');
      return it;
    };

    var $$g = _export;
    var toObject$2 = toObject$c;
    var toAbsoluteIndex$1 = toAbsoluteIndex$7;
    var toIntegerOrInfinity = toIntegerOrInfinity$9;
    var lengthOfArrayLike$1 = lengthOfArrayLike$e;
    var setArrayLength = arraySetLength;
    var doesNotExceedSafeInteger = doesNotExceedSafeInteger$1;
    var arraySpeciesCreate = arraySpeciesCreate$2;
    var createProperty$1 = createProperty$3;
    var deletePropertyOrThrow = deletePropertyOrThrow$2;
    var arrayMethodHasSpeciesSupport$2 = arrayMethodHasSpeciesSupport$4;

    var HAS_SPECIES_SUPPORT$2 = arrayMethodHasSpeciesSupport$2('splice');

    var max$1 = Math.max;
    var min$2 = Math.min;

    // `Array.prototype.splice` method
    // https://tc39.es/ecma262/#sec-array.prototype.splice
    // with adding support of @@species
    $$g({ target: 'Array', proto: true, forced: !HAS_SPECIES_SUPPORT$2 }, {
      splice: function splice(start, deleteCount /* , ...items */) {
        var O = toObject$2(this);
        var len = lengthOfArrayLike$1(O);
        var actualStart = toAbsoluteIndex$1(start, len);
        var argumentsLength = arguments.length;
        var insertCount, actualDeleteCount, A, k, from, to;
        if (argumentsLength === 0) {
          insertCount = actualDeleteCount = 0;
        } else if (argumentsLength === 1) {
          insertCount = 0;
          actualDeleteCount = len - actualStart;
        } else {
          insertCount = argumentsLength - 2;
          actualDeleteCount = min$2(max$1(toIntegerOrInfinity(deleteCount), 0), len - actualStart);
        }
        doesNotExceedSafeInteger(len + insertCount - actualDeleteCount);
        A = arraySpeciesCreate(O, actualDeleteCount);
        for (k = 0; k < actualDeleteCount; k++) {
          from = actualStart + k;
          if (from in O) createProperty$1(A, k, O[from]);
        }
        A.length = actualDeleteCount;
        if (insertCount < actualDeleteCount) {
          for (k = actualStart; k < len - actualDeleteCount; k++) {
            from = k + actualDeleteCount;
            to = k + insertCount;
            if (from in O) O[to] = O[from];
            else deletePropertyOrThrow(O, to);
          }
          for (k = len; k > len - actualDeleteCount + insertCount; k--) deletePropertyOrThrow(O, k - 1);
        } else if (insertCount > actualDeleteCount) {
          for (k = len - actualDeleteCount; k > actualStart; k--) {
            from = k + actualDeleteCount - 1;
            to = k + insertCount - 1;
            if (from in O) O[to] = O[from];
            else deletePropertyOrThrow(O, to);
          }
        }
        for (k = 0; k < insertCount; k++) {
          O[k + actualStart] = arguments[k + 2];
        }
        setArrayLength(O, len - actualDeleteCount + insertCount);
        return A;
      }
    });

    var $$f = _export;
    var isArray = isArray$4;
    var isConstructor = isConstructor$4;
    var isObject = isObject$h;
    var toAbsoluteIndex = toAbsoluteIndex$7;
    var lengthOfArrayLike = lengthOfArrayLike$e;
    var toIndexedObject$1 = toIndexedObject$a;
    var createProperty = createProperty$3;
    var wellKnownSymbol$2 = wellKnownSymbol$n;
    var arrayMethodHasSpeciesSupport$1 = arrayMethodHasSpeciesSupport$4;
    var nativeSlice = arraySlice$6;

    var HAS_SPECIES_SUPPORT$1 = arrayMethodHasSpeciesSupport$1('slice');

    var SPECIES = wellKnownSymbol$2('species');
    var $Array = Array;
    var max = Math.max;

    // `Array.prototype.slice` method
    // https://tc39.es/ecma262/#sec-array.prototype.slice
    // fallback for not array-like ES3 strings and DOM objects
    $$f({ target: 'Array', proto: true, forced: !HAS_SPECIES_SUPPORT$1 }, {
      slice: function slice(start, end) {
        var O = toIndexedObject$1(this);
        var length = lengthOfArrayLike(O);
        var k = toAbsoluteIndex(start, length);
        var fin = toAbsoluteIndex(end === undefined ? length : end, length);
        // inline `ArraySpeciesCreate` for usage native `Array#slice` where it's possible
        var Constructor, result, n;
        if (isArray(O)) {
          Constructor = O.constructor;
          // cross-realm fallback
          if (isConstructor(Constructor) && (Constructor === $Array || isArray(Constructor.prototype))) {
            Constructor = undefined;
          } else if (isObject(Constructor)) {
            Constructor = Constructor[SPECIES];
            if (Constructor === null) Constructor = undefined;
          }
          if (Constructor === $Array || Constructor === undefined) {
            return nativeSlice(O, k, fin);
          }
        }
        result = new (Constructor === undefined ? $Array : Constructor)(max(fin - k, 0));
        for (n = 0; k < fin; k++, n++) if (k in O) createProperty(result, n, O[k]);
        result.length = n;
        return result;
      }
    });

    var $$e = _export;
    var $find = arrayIteration.find;
    var addToUnscopables$1 = addToUnscopables$4;

    var FIND = 'find';
    var SKIPS_HOLES = true;

    // Shouldn't skip holes
    // eslint-disable-next-line es/no-array-prototype-find -- testing
    if (FIND in []) Array(1)[FIND](function () { SKIPS_HOLES = false; });

    // `Array.prototype.find` method
    // https://tc39.es/ecma262/#sec-array.prototype.find
    $$e({ target: 'Array', proto: true, forced: SKIPS_HOLES }, {
      find: function find(callbackfn /* , that = undefined */) {
        return $find(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined);
      }
    });

    // https://tc39.es/ecma262/#sec-array.prototype-@@unscopables
    addToUnscopables$1(FIND);

    var isRegExp = isRegexp;

    var $TypeError = TypeError;

    var notARegexp = function (it) {
      if (isRegExp(it)) {
        throw new $TypeError("The method doesn't accept regular expressions");
      } return it;
    };

    var wellKnownSymbol$1 = wellKnownSymbol$n;

    var MATCH = wellKnownSymbol$1('match');

    var correctIsRegexpLogic = function (METHOD_NAME) {
      var regexp = /./;
      try {
        '/./'[METHOD_NAME](regexp);
      } catch (error1) {
        try {
          regexp[MATCH] = false;
          return '/./'[METHOD_NAME](regexp);
        } catch (error2) { /* empty */ }
      } return false;
    };

    var $$d = _export;
    var uncurryThis$5 = functionUncurryThisClause;
    var getOwnPropertyDescriptor$1 = objectGetOwnPropertyDescriptor.f;
    var toLength$1 = toLength$9;
    var toString$2 = toString$c;
    var notARegExp$2 = notARegexp;
    var requireObjectCoercible$2 = requireObjectCoercible$9;
    var correctIsRegExpLogic$2 = correctIsRegexpLogic;

    var slice = uncurryThis$5(''.slice);
    var min$1 = Math.min;

    var CORRECT_IS_REGEXP_LOGIC$1 = correctIsRegExpLogic$2('endsWith');
    // https://github.com/zloirock/core-js/pull/702
    var MDN_POLYFILL_BUG$1 = !CORRECT_IS_REGEXP_LOGIC$1 && !!function () {
      var descriptor = getOwnPropertyDescriptor$1(String.prototype, 'endsWith');
      return descriptor && !descriptor.writable;
    }();

    // `String.prototype.endsWith` method
    // https://tc39.es/ecma262/#sec-string.prototype.endswith
    $$d({ target: 'String', proto: true, forced: !MDN_POLYFILL_BUG$1 && !CORRECT_IS_REGEXP_LOGIC$1 }, {
      endsWith: function endsWith(searchString /* , endPosition = @length */) {
        var that = toString$2(requireObjectCoercible$2(this));
        notARegExp$2(searchString);
        var endPosition = arguments.length > 1 ? arguments[1] : undefined;
        var len = that.length;
        var end = endPosition === undefined ? len : min$1(toLength$1(endPosition), len);
        var search = toString$2(searchString);
        return slice(that, end - search.length, end) === search;
      }
    });

    var $$c = _export;
    var $includes = arrayIncludes.includes;
    var fails$3 = fails$C;
    var addToUnscopables = addToUnscopables$4;

    // FF99+ bug
    var BROKEN_ON_SPARSE = fails$3(function () {
      // eslint-disable-next-line es/no-array-prototype-includes -- detection
      return !Array(1).includes();
    });

    // `Array.prototype.includes` method
    // https://tc39.es/ecma262/#sec-array.prototype.includes
    $$c({ target: 'Array', proto: true, forced: BROKEN_ON_SPARSE }, {
      includes: function includes(el /* , fromIndex = 0 */) {
        return $includes(this, el, arguments.length > 1 ? arguments[1] : undefined);
      }
    });

    // https://tc39.es/ecma262/#sec-array.prototype-@@unscopables
    addToUnscopables('includes');

    var $$b = _export;
    var uncurryThis$4 = functionUncurryThis;
    var notARegExp$1 = notARegexp;
    var requireObjectCoercible$1 = requireObjectCoercible$9;
    var toString$1 = toString$c;
    var correctIsRegExpLogic$1 = correctIsRegexpLogic;

    var stringIndexOf = uncurryThis$4(''.indexOf);

    // `String.prototype.includes` method
    // https://tc39.es/ecma262/#sec-string.prototype.includes
    $$b({ target: 'String', proto: true, forced: !correctIsRegExpLogic$1('includes') }, {
      includes: function includes(searchString /* , position = 0 */) {
        return !!~stringIndexOf(
          toString$1(requireObjectCoercible$1(this)),
          toString$1(notARegExp$1(searchString)),
          arguments.length > 1 ? arguments[1] : undefined
        );
      }
    });

    var $$a = _export;
    var uncurryThis$3 = functionUncurryThisClause;
    var getOwnPropertyDescriptor = objectGetOwnPropertyDescriptor.f;
    var toLength = toLength$9;
    var toString = toString$c;
    var notARegExp = notARegexp;
    var requireObjectCoercible = requireObjectCoercible$9;
    var correctIsRegExpLogic = correctIsRegexpLogic;

    var stringSlice = uncurryThis$3(''.slice);
    var min = Math.min;

    var CORRECT_IS_REGEXP_LOGIC = correctIsRegExpLogic('startsWith');
    // https://github.com/zloirock/core-js/pull/702
    var MDN_POLYFILL_BUG = !CORRECT_IS_REGEXP_LOGIC && !!function () {
      var descriptor = getOwnPropertyDescriptor(String.prototype, 'startsWith');
      return descriptor && !descriptor.writable;
    }();

    // `String.prototype.startsWith` method
    // https://tc39.es/ecma262/#sec-string.prototype.startswith
    $$a({ target: 'String', proto: true, forced: !MDN_POLYFILL_BUG && !CORRECT_IS_REGEXP_LOGIC }, {
      startsWith: function startsWith(searchString /* , position = 0 */) {
        var that = toString(requireObjectCoercible(this));
        notARegExp(searchString);
        var index = toLength(min(arguments.length > 1 ? arguments[1] : undefined, that.length));
        var search = toString(searchString);
        return stringSlice(that, index, index + search.length) === search;
      }
    });

    var createTypedArrayConstructor$6 = typedArrayConstructor.exports;

    // `Int8Array` constructor
    // https://tc39.es/ecma262/#sec-typedarray-objects
    createTypedArrayConstructor$6('Int8', function (init) {
      return function Int8Array(data, byteOffset, length) {
        return init(this, data, byteOffset, length);
      };
    });

    var createTypedArrayConstructor$5 = typedArrayConstructor.exports;

    // `Int16Array` constructor
    // https://tc39.es/ecma262/#sec-typedarray-objects
    createTypedArrayConstructor$5('Int16', function (init) {
      return function Int16Array(data, byteOffset, length) {
        return init(this, data, byteOffset, length);
      };
    });

    var createTypedArrayConstructor$4 = typedArrayConstructor.exports;

    // `Int32Array` constructor
    // https://tc39.es/ecma262/#sec-typedarray-objects
    createTypedArrayConstructor$4('Int32', function (init) {
      return function Int32Array(data, byteOffset, length) {
        return init(this, data, byteOffset, length);
      };
    });

    var createTypedArrayConstructor$3 = typedArrayConstructor.exports;

    // `Uint16Array` constructor
    // https://tc39.es/ecma262/#sec-typedarray-objects
    createTypedArrayConstructor$3('Uint16', function (init) {
      return function Uint16Array(data, byteOffset, length) {
        return init(this, data, byteOffset, length);
      };
    });

    var createTypedArrayConstructor$2 = typedArrayConstructor.exports;

    // `Uint32Array` constructor
    // https://tc39.es/ecma262/#sec-typedarray-objects
    createTypedArrayConstructor$2('Uint32', function (init) {
      return function Uint32Array(data, byteOffset, length) {
        return init(this, data, byteOffset, length);
      };
    });

    var createTypedArrayConstructor$1 = typedArrayConstructor.exports;

    // `Float32Array` constructor
    // https://tc39.es/ecma262/#sec-typedarray-objects
    createTypedArrayConstructor$1('Float32', function (init) {
      return function Float32Array(data, byteOffset, length) {
        return init(this, data, byteOffset, length);
      };
    });

    var createTypedArrayConstructor = typedArrayConstructor.exports;

    // `Float64Array` constructor
    // https://tc39.es/ecma262/#sec-typedarray-objects
    createTypedArrayConstructor('Float64', function (init) {
      return function Float64Array(data, byteOffset, length) {
        return init(this, data, byteOffset, length);
      };
    });

    var $$9 = _export;
    var $map = arrayIteration.map;
    var arrayMethodHasSpeciesSupport = arrayMethodHasSpeciesSupport$4;

    var HAS_SPECIES_SUPPORT = arrayMethodHasSpeciesSupport('map');

    // `Array.prototype.map` method
    // https://tc39.es/ecma262/#sec-array.prototype.map
    // with adding support of @@species
    $$9({ target: 'Array', proto: true, forced: !HAS_SPECIES_SUPPORT }, {
      map: function map(callbackfn /* , thisArg */) {
        return $map(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined);
      }
    });

    var DESCRIPTORS$1 = descriptors;
    var uncurryThis$2 = functionUncurryThis;
    var call$1 = functionCall;
    var fails$2 = fails$C;
    var objectKeys$1 = objectKeys$3;
    var getOwnPropertySymbolsModule = objectGetOwnPropertySymbols;
    var propertyIsEnumerableModule = objectPropertyIsEnumerable;
    var toObject$1 = toObject$c;
    var IndexedObject = indexedObject;

    // eslint-disable-next-line es/no-object-assign -- safe
    var $assign = Object.assign;
    // eslint-disable-next-line es/no-object-defineproperty -- required for testing
    var defineProperty = Object.defineProperty;
    var concat = uncurryThis$2([].concat);

    // `Object.assign` method
    // https://tc39.es/ecma262/#sec-object.assign
    var objectAssign = !$assign || fails$2(function () {
      // should have correct order of operations (Edge bug)
      if (DESCRIPTORS$1 && $assign({ b: 1 }, $assign(defineProperty({}, 'a', {
        enumerable: true,
        get: function () {
          defineProperty(this, 'b', {
            value: 3,
            enumerable: false
          });
        }
      }), { b: 2 })).b !== 1) return true;
      // should work with symbols and should have deterministic property order (V8 bug)
      var A = {};
      var B = {};
      // eslint-disable-next-line es/no-symbol -- safe
      var symbol = Symbol('assign detection');
      var alphabet = 'abcdefghijklmnopqrst';
      A[symbol] = 7;
      alphabet.split('').forEach(function (chr) { B[chr] = chr; });
      return $assign({}, A)[symbol] !== 7 || objectKeys$1($assign({}, B)).join('') !== alphabet;
    }) ? function assign(target, source) { // eslint-disable-line no-unused-vars -- required for `.length`
      var T = toObject$1(target);
      var argumentsLength = arguments.length;
      var index = 1;
      var getOwnPropertySymbols = getOwnPropertySymbolsModule.f;
      var propertyIsEnumerable = propertyIsEnumerableModule.f;
      while (argumentsLength > index) {
        var S = IndexedObject(arguments[index++]);
        var keys = getOwnPropertySymbols ? concat(objectKeys$1(S), getOwnPropertySymbols(S)) : objectKeys$1(S);
        var length = keys.length;
        var j = 0;
        var key;
        while (length > j) {
          key = keys[j++];
          if (!DESCRIPTORS$1 || call$1(propertyIsEnumerable, S, key)) T[key] = S[key];
        }
      } return T;
    } : $assign;

    var $$8 = _export;
    var assign = objectAssign;

    // `Object.assign` method
    // https://tc39.es/ecma262/#sec-object.assign
    // eslint-disable-next-line es/no-object-assign -- required for testing
    $$8({ target: 'Object', stat: true, arity: 2, forced: Object.assign !== assign }, {
      assign: assign
    });

    /* eslint-disable es/no-array-prototype-indexof -- required for testing */
    var $$7 = _export;
    var uncurryThis$1 = functionUncurryThisClause;
    var $indexOf = arrayIncludes.indexOf;
    var arrayMethodIsStrict = arrayMethodIsStrict$4;

    var nativeIndexOf = uncurryThis$1([].indexOf);

    var NEGATIVE_ZERO = !!nativeIndexOf && 1 / nativeIndexOf([1], 1, -0) < 0;
    var FORCED = NEGATIVE_ZERO || !arrayMethodIsStrict('indexOf');

    // `Array.prototype.indexOf` method
    // https://tc39.es/ecma262/#sec-array.prototype.indexof
    $$7({ target: 'Array', proto: true, forced: FORCED }, {
      indexOf: function indexOf(searchElement /* , fromIndex = 0 */) {
        var fromIndex = arguments.length > 1 ? arguments[1] : undefined;
        return NEGATIVE_ZERO
          // convert -0 to +0
          ? nativeIndexOf(this, searchElement, fromIndex) || 0
          : $indexOf(this, searchElement, fromIndex);
      }
    });

    var globalThis$2 = globalThis_1;
    var DOMIterables = domIterables;
    var DOMTokenListPrototype = domTokenListPrototype;
    var ArrayIteratorMethods = es_array_iterator;
    var createNonEnumerableProperty = createNonEnumerableProperty$a;
    var setToStringTag = setToStringTag$5;
    var wellKnownSymbol = wellKnownSymbol$n;

    var ITERATOR = wellKnownSymbol('iterator');
    var ArrayValues = ArrayIteratorMethods.values;

    var handlePrototype = function (CollectionPrototype, COLLECTION_NAME) {
      if (CollectionPrototype) {
        // some Chrome versions have non-configurable methods on DOMTokenList
        if (CollectionPrototype[ITERATOR] !== ArrayValues) try {
          createNonEnumerableProperty(CollectionPrototype, ITERATOR, ArrayValues);
        } catch (error) {
          CollectionPrototype[ITERATOR] = ArrayValues;
        }
        setToStringTag(CollectionPrototype, COLLECTION_NAME, true);
        if (DOMIterables[COLLECTION_NAME]) for (var METHOD_NAME in ArrayIteratorMethods) {
          // some Chrome versions have non-configurable methods on DOMTokenList
          if (CollectionPrototype[METHOD_NAME] !== ArrayIteratorMethods[METHOD_NAME]) try {
            createNonEnumerableProperty(CollectionPrototype, METHOD_NAME, ArrayIteratorMethods[METHOD_NAME]);
          } catch (error) {
            CollectionPrototype[METHOD_NAME] = ArrayIteratorMethods[METHOD_NAME];
          }
        }
      }
    };

    for (var COLLECTION_NAME in DOMIterables) {
      handlePrototype(globalThis$2[COLLECTION_NAME] && globalThis$2[COLLECTION_NAME].prototype, COLLECTION_NAME);
    }

    handlePrototype(DOMTokenListPrototype, 'DOMTokenList');

    var $$6 = _export;
    var globalThis$1 = globalThis_1;
    var arrayBufferModule = arrayBuffer;
    var setSpecies = setSpecies$4;

    var ARRAY_BUFFER = 'ArrayBuffer';
    var ArrayBuffer$1 = arrayBufferModule[ARRAY_BUFFER];
    var NativeArrayBuffer = globalThis$1[ARRAY_BUFFER];

    // `ArrayBuffer` constructor
    // https://tc39.es/ecma262/#sec-arraybuffer-constructor
    $$6({ global: true, constructor: true, forced: NativeArrayBuffer !== ArrayBuffer$1 }, {
      ArrayBuffer: ArrayBuffer$1
    });

    setSpecies(ARRAY_BUFFER);

    var $$5 = _export;
    var ArrayBufferViewCore = arrayBufferViewCore;

    var NATIVE_ARRAY_BUFFER_VIEWS = ArrayBufferViewCore.NATIVE_ARRAY_BUFFER_VIEWS;

    // `ArrayBuffer.isView` method
    // https://tc39.es/ecma262/#sec-arraybuffer.isview
    $$5({ target: 'ArrayBuffer', stat: true, forced: !NATIVE_ARRAY_BUFFER_VIEWS }, {
      isView: ArrayBufferViewCore.isView
    });

    var $$4 = _export;
    var call = functionCall;

    // `URL.prototype.toJSON` method
    // https://url.spec.whatwg.org/#dom-url-tojson
    $$4({ target: 'URL', proto: true, enumerable: true }, {
      toJSON: function toJSON() {
        return call(URL.prototype.toString, this);
      }
    });

    var DESCRIPTORS = descriptors;
    var fails$1 = fails$C;
    var uncurryThis = functionUncurryThis;
    var objectGetPrototypeOf = objectGetPrototypeOf$1;
    var objectKeys = objectKeys$3;
    var toIndexedObject = toIndexedObject$a;
    var $propertyIsEnumerable = objectPropertyIsEnumerable.f;

    var propertyIsEnumerable = uncurryThis($propertyIsEnumerable);
    var push = uncurryThis([].push);

    // in some IE versions, `propertyIsEnumerable` returns incorrect result on integer keys
    // of `null` prototype objects
    var IE_BUG = DESCRIPTORS && fails$1(function () {
      // eslint-disable-next-line es/no-object-create -- safe
      var O = Object.create(null);
      O[2] = 2;
      return !propertyIsEnumerable(O, 2);
    });

    // `Object.{ entries, values }` methods implementation
    var createMethod = function (TO_ENTRIES) {
      return function (it) {
        var O = toIndexedObject(it);
        var keys = objectKeys(O);
        var IE_WORKAROUND = IE_BUG && objectGetPrototypeOf(O) === null;
        var length = keys.length;
        var i = 0;
        var result = [];
        var key;
        while (length > i) {
          key = keys[i++];
          if (!DESCRIPTORS || (IE_WORKAROUND ? key in O : propertyIsEnumerable(O, key))) {
            push(result, TO_ENTRIES ? [key, O[key]] : O[key]);
          }
        }
        return result;
      };
    };

    var objectToArray = {
      // `Object.entries` method
      // https://tc39.es/ecma262/#sec-object.entries
      entries: createMethod(true),
      // `Object.values` method
      // https://tc39.es/ecma262/#sec-object.values
      values: createMethod(false)
    };

    var $$3 = _export;
    var $entries = objectToArray.entries;

    // `Object.entries` method
    // https://tc39.es/ecma262/#sec-object.entries
    $$3({ target: 'Object', stat: true }, {
      entries: function entries(O) {
        return $entries(O);
      }
    });

    var $$2 = _export;
    var isIntegralNumber = isIntegralNumber$2;

    // `Number.isInteger` method
    // https://tc39.es/ecma262/#sec-number.isinteger
    $$2({ target: 'Number', stat: true }, {
      isInteger: isIntegralNumber
    });

    var $$1 = _export;
    var fails = fails$C;
    var toObject = toObject$c;
    var nativeGetPrototypeOf = objectGetPrototypeOf$1;
    var CORRECT_PROTOTYPE_GETTER = correctPrototypeGetter;

    var FAILS_ON_PRIMITIVES = fails(function () { nativeGetPrototypeOf(1); });

    // `Object.getPrototypeOf` method
    // https://tc39.es/ecma262/#sec-object.getprototypeof
    $$1({ target: 'Object', stat: true, forced: FAILS_ON_PRIMITIVES, sham: !CORRECT_PROTOTYPE_GETTER }, {
      getPrototypeOf: function getPrototypeOf(it) {
        return nativeGetPrototypeOf(toObject(it));
      }
    });

    var $ = _export;
    var $parseInt = numberParseInt;

    // `parseInt` method
    // https://tc39.es/ecma262/#sec-parseint-string-radix
    $({ global: true, forced: parseInt !== $parseInt }, {
      parseInt: $parseInt
    });

    /*!
     * TSBuffer Schema v2.2.0
     * -----------------------------------------
     * MIT LICENSE
     * KingWorks (C) Copyright 2022
     * https://github.com/k8w/tsbuffer-schema
     */
    /**
     * Enum for every possible `TSBufferSchema['type']`
     */
    var SchemaType = /** @class */ (function () {
        function SchemaType() {
        }
        // #region 确定的TypeScript的类型
        SchemaType.Boolean = 'Boolean';
        SchemaType.Number = 'Number';
        SchemaType.String = 'String';
        SchemaType.Array = 'Array';
        SchemaType.Tuple = 'Tuple';
        SchemaType.Enum = 'Enum';
        SchemaType.Any = 'Any';
        SchemaType.Literal = 'Literal';
        SchemaType.Object = 'Object';
        SchemaType.Interface = 'Interface';
        SchemaType.Buffer = 'Buffer';
        SchemaType.IndexedAccess = 'IndexedAccess';
        SchemaType.Reference = 'Reference';
        SchemaType.Keyof = 'Keyof';
        SchemaType.Union = 'Union';
        SchemaType.Intersection = 'Intersection';
        SchemaType.NonNullable = 'NonNullable';
        SchemaType.Date = 'Date';
        // #endregion
        // #region 非TypeScript基本类型，临时过渡用
        SchemaType.Pick = 'Pick';
        SchemaType.Partial = 'Partial';
        SchemaType.Omit = 'Omit';
        SchemaType.Overwrite = 'Overwrite';
        // #endregion
        SchemaType.Custom = 'Custom';
        return SchemaType;
    }());

    /******************************************************************************
    Copyright (c) Microsoft Corporation.

    Permission to use, copy, modify, and/or distribute this software for any
    purpose with or without fee is hereby granted.

    THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
    REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
    AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
    INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
    LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
    OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
    PERFORMANCE OF THIS SOFTWARE.
    ***************************************************************************** */
    /* global Reflect, Promise, SuppressedError, Symbol, Iterator */

    var extendStatics = function(d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };

    function __extends(d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    }

    var __assign = function() {
        __assign = Object.assign || function __assign(t) {
            for (var s, i = 1, n = arguments.length; i < n; i++) {
                s = arguments[i];
                for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
            }
            return t;
        };
        return __assign.apply(this, arguments);
    };

    function __awaiter(thisArg, _arguments, P, generator) {
        function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
        return new (P || (P = Promise))(function (resolve, reject) {
            function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
            function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
            function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
            step((generator = generator.apply(thisArg, _arguments || [])).next());
        });
    }

    function __generator(thisArg, body) {
        var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
        return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
        function verb(n) { return function (v) { return step([n, v]); }; }
        function step(op) {
            if (f) throw new TypeError("Generator is already executing.");
            while (g && (g = 0, op[0] && (_ = 0)), _) try {
                if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
                if (y = 0, t) op = [op[0] & 2, t.value];
                switch (op[0]) {
                    case 0: case 1: t = op; break;
                    case 4: _.label++; return { value: op[1], done: false };
                    case 5: _.label++; y = op[1]; op = [0]; continue;
                    case 7: op = _.ops.pop(); _.trys.pop(); continue;
                    default:
                        if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                        if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                        if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                        if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                        if (t[2]) _.ops.pop();
                        _.trys.pop(); continue;
                }
                op = body.call(thisArg, _);
            } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
            if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
        }
    }

    typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
        var e = new Error(message);
        return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
    };

    /*!
     * TSRPC Proto v1.4.3
     * -----------------------------------------
     * Copyright (c) Kingworks Corporation.
     * MIT License
     * https://github.com/k8w/tsrpc-proto
     */

    var empty = function () { };
    function setLogLevel(logger, logLevel) {
        switch (logLevel) {
            case 'none':
                return { debug: empty, log: empty, warn: empty, error: empty };
            case 'error':
                return { debug: empty, log: empty, warn: empty, error: logger.error.bind(logger) };
            case 'warn':
                return { debug: empty, log: empty, warn: logger.warn.bind(logger), error: logger.error.bind(logger) };
            case 'info':
                return { debug: empty, log: logger.log.bind(logger), warn: logger.warn.bind(logger), error: logger.error.bind(logger) };
            case 'debug':
                return logger;
            default:
                throw new Error("Invalid logLevel: '".concat(logLevel, "'"));
        }
    }

    exports.TsrpcErrorType = void 0;
    (function (TsrpcErrorType) {
        /** Network error, like connection broken, network timeout, etc. */
        TsrpcErrorType["NetworkError"] = "NetworkError";
        /**
         * Server exception, for example "request format error", "database exception", etc.
         *
         * @remarks
         * This error message may be not suitable to show to user,
         * but the error info is useful for engineer to find some bug.
         * So you can show a user-friendly message to user (like "System error, please contact XXX"),
         * and report some debug info at the same time.
         */
        TsrpcErrorType["ServerError"] = "ServerError";
        /** Client exception, for example parse server output error.
         * (May because of the proto file is not the same between server and client)
         */
        TsrpcErrorType["ClientError"] = "ClientError";
        /**
         * The business error returned by `call.error`.
         * It is always business-relatived, for example `call.error('Password is incorrect')`, `call.error('Not enough credit')`, etc.
         */
        TsrpcErrorType["ApiError"] = "ApiError";
    })(exports.TsrpcErrorType || (exports.TsrpcErrorType = {}));

    var TransportDataProto = {
        "ServerInputData": {
            "type": SchemaType.Interface,
            "properties": [
                {
                    "id": 0,
                    "name": "serviceId",
                    "type": {
                        "type": SchemaType.Number,
                        "scalarType": "uint"
                    }
                },
                {
                    "id": 1,
                    "name": "buffer",
                    "type": {
                        "type": SchemaType.Buffer,
                        "arrayType": "Uint8Array"
                    }
                },
                {
                    "id": 2,
                    "name": "sn",
                    "type": {
                        "type": SchemaType.Number,
                        "scalarType": "uint"
                    },
                    "optional": true
                }
            ]
        },
        "ServerOutputData": {
            "type": SchemaType.Interface,
            "properties": [
                {
                    "id": 0,
                    "name": "buffer",
                    "type": {
                        "type": SchemaType.Buffer,
                        "arrayType": "Uint8Array"
                    },
                    "optional": true
                },
                {
                    "id": 1,
                    "name": "error",
                    "type": {
                        "type": SchemaType.Reference,
                        "target": "TsrpcErrorData"
                    },
                    "optional": true
                },
                {
                    "id": 2,
                    "name": "serviceId",
                    "type": {
                        "type": SchemaType.Number,
                        "scalarType": "uint"
                    },
                    "optional": true
                },
                {
                    "id": 3,
                    "name": "sn",
                    "type": {
                        "type": SchemaType.Number,
                        "scalarType": "uint"
                    },
                    "optional": true
                }
            ]
        },
        "TsrpcErrorData": {
            "type": SchemaType.Interface,
            "properties": [
                {
                    "id": 0,
                    "name": "message",
                    "type": {
                        "type": SchemaType.String
                    }
                },
                {
                    "id": 1,
                    "name": "type",
                    "type": {
                        "type": SchemaType.Reference,
                        "target": "TsrpcErrorType"
                    }
                },
                {
                    "id": 2,
                    "name": "code",
                    "type": {
                        "type": SchemaType.Union,
                        "members": [
                            {
                                "id": 0,
                                "type": {
                                    "type": SchemaType.String
                                }
                            },
                            {
                                "id": 1,
                                "type": {
                                    "type": SchemaType.Number,
                                    "scalarType": "int"
                                }
                            }
                        ]
                    },
                    "optional": true
                }
            ],
            "indexSignature": {
                "keyType": "String",
                "type": {
                    "type": SchemaType.Any
                }
            }
        },
        "TsrpcErrorType": {
            "type": SchemaType.Enum,
            "members": [
                {
                    "id": 0,
                    "value": "NetworkError"
                },
                {
                    "id": 1,
                    "value": "ServerError"
                },
                {
                    "id": 2,
                    "value": "ClientError"
                },
                {
                    "id": 3,
                    "value": "ApiError"
                }
            ]
        }
    };

    /**
     * A unified Error that returned by TSRPC server or client
     *
     * @remarks
     * It has many uses, for example:
     *
     * 1. You can handle business errors and network errors uniformly.
     * 2. In API handle process, `throw new TsrpcError('xxx')` would return the same error to client directly (like `call.error()`),
     * while `throw new Error('XXX')` would return a unified "Server Internal Error".
     */
    var TsrpcError = /** @class */ (function () {
        function TsrpcError(dataOrMessage, data) {
            var _a;
            if (typeof dataOrMessage === 'string') {
                this.message = dataOrMessage;
                this.type = (_a = data === null || data === void 0 ? void 0 : data.type) !== null && _a !== void 0 ? _a : exports.TsrpcErrorType.ApiError;
                __assign(this, data);
            }
            else {
                __assign(this, dataOrMessage);
            }
        }
        TsrpcError.prototype.toString = function () {
            return "[TSRPC ".concat(this.type, "]: ").concat(this.message);
        };
        TsrpcError.Type = exports.TsrpcErrorType;
        return TsrpcError;
    }());

    /*!
     * TSBuffer Validator v2.1.2
     * -----------------------------------------
     * MIT LICENSE
     * KingWorks (C) Copyright 2023
     * https://github.com/k8w/tsbuffer-validator
     */

    var ProtoHelper = /** @class */ (function () {
        function ProtoHelper(proto) {
            this._schemaWithUuids = [];
            this._unionPropertiesCache = {};
            this._flatInterfaceSchemaCache = {};
            this._parseMappedTypeCache = new WeakMap();
            this.proto = proto;
        }
        /** 将ReferenceTypeSchema层层转换为它最终实际引用的类型 */
        ProtoHelper.prototype.parseReference = function (schema) {
            // Reference
            if (schema.type === SchemaType.Reference) {
                var parsedSchema = this.proto[schema.target];
                if (!parsedSchema) {
                    throw new Error("Cannot find reference target: ".concat(schema.target));
                }
                if (this.isTypeReference(parsedSchema)) {
                    return this.parseReference(parsedSchema);
                }
                else {
                    return parsedSchema;
                }
            }
            // IndexedAccess
            else if (schema.type === SchemaType.IndexedAccess) {
                if (!this.isInterface(schema.objectType)) {
                    throw new Error("Error objectType: ".concat(schema.objectType.type));
                }
                // find prop item
                var flat = this.getFlatInterfaceSchema(schema.objectType);
                var propItem = flat.properties.find(function (v) { return v.name === schema.index; });
                var propType = void 0;
                if (propItem) {
                    propType = propItem.type;
                }
                else {
                    if (flat.indexSignature) {
                        propType = flat.indexSignature.type;
                    }
                    else {
                        throw new Error("Error index: ".concat(schema.index));
                    }
                }
                // optional -> | undefined
                if (propItem && propItem.optional && // 引用的字段是optional
                    (propItem.type.type !== SchemaType.Union // 自身不为Union
                        // 或自身为Union，但没有undefined成员条件
                        || propItem.type.members.findIndex(function (v) { return v.type.type === SchemaType.Literal && v.type.literal === undefined; }) === -1)) {
                    propType = {
                        type: SchemaType.Union,
                        members: [
                            { id: 0, type: propType },
                            {
                                id: 1,
                                type: {
                                    type: SchemaType.Literal,
                                    literal: undefined
                                }
                            }
                        ]
                    };
                }
                return this.isTypeReference(propType) ? this.parseReference(propType) : propType;
            }
            else if (schema.type === SchemaType.Keyof) {
                var flatInterface = this.getFlatInterfaceSchema(schema.target);
                return {
                    type: SchemaType.Union,
                    members: flatInterface.properties.map(function (v, i) { return ({
                        id: i,
                        type: {
                            type: SchemaType.Literal,
                            literal: v.name
                        }
                    }); })
                };
            }
            else {
                return schema;
            }
        };
        ProtoHelper.prototype.isInterface = function (schema, excludeReference) {
            if (excludeReference === void 0) { excludeReference = false; }
            if (!excludeReference && this.isTypeReference(schema)) {
                var parsed = this.parseReference(schema);
                return this.isInterface(parsed, excludeReference);
            }
            else {
                return schema.type === SchemaType.Interface || this.isMappedType(schema) && this.parseMappedType(schema).type === SchemaType.Interface;
            }
        };
        ProtoHelper.prototype.isMappedType = function (schema) {
            return schema.type === SchemaType.Pick ||
                schema.type === SchemaType.Partial ||
                schema.type === SchemaType.Omit ||
                schema.type === SchemaType.Overwrite;
        };
        ProtoHelper.prototype.isTypeReference = function (schema) {
            return schema.type === SchemaType.Reference || schema.type === SchemaType.IndexedAccess || schema.type === SchemaType.Keyof;
        };
        ProtoHelper.prototype._getSchemaUuid = function (schema) {
            var schemaWithUuid = schema;
            if (!schemaWithUuid.uuid) {
                schemaWithUuid.uuid = this._schemaWithUuids.push(schemaWithUuid);
            }
            return schemaWithUuid.uuid;
        };
        ProtoHelper.prototype.getUnionProperties = function (schema) {
            var uuid = this._getSchemaUuid(schema);
            if (!this._unionPropertiesCache[uuid]) {
                this._unionPropertiesCache[uuid] = this._addUnionProperties([], schema.members.map(function (v) { return v.type; }));
            }
            return this._unionPropertiesCache[uuid];
        };
        /**
         * unionProperties: 在Union或Intersection类型中，出现在任意member中的字段
         */
        ProtoHelper.prototype._addUnionProperties = function (unionProperties, schemas) {
            for (var i = 0, len = schemas.length; i < len; ++i) {
                var schema = this.parseReference(schemas[i]);
                // Interface及其Ref 加入interfaces
                if (this.isInterface(schema)) {
                    var flat = this.getFlatInterfaceSchema(schema);
                    flat.properties.forEach(function (v) {
                        unionProperties.binaryInsert(v.name, true);
                    });
                    if (flat.indexSignature) {
                        var key = "[[".concat(flat.indexSignature.keyType, "]]");
                        unionProperties.binaryInsert(key, true);
                    }
                }
                // Intersection/Union 递归合并unionProperties
                else if (schema.type === SchemaType.Intersection || schema.type === SchemaType.Union) {
                    this._addUnionProperties(unionProperties, schema.members.map(function (v) { return v.type; }));
                }
                else if (this.isMappedType(schema)) {
                    this._addUnionProperties(unionProperties, [this.parseMappedType(schema)]);
                }
            }
            return unionProperties;
        };
        /**
         * 将unionProperties 扩展到 InterfaceTypeSchema中（optional的any类型）
         * 以此来跳过对它们的检查（用于Intersection/Union）
         */
        ProtoHelper.prototype.applyUnionProperties = function (schema, unionProperties) {
            var newSchema = __assign(__assign({}, schema), { properties: schema.properties.slice() });
            var _loop_1 = function (prop) {
                if (prop === '[[String]]') {
                    newSchema.indexSignature = newSchema.indexSignature || {
                        keyType: SchemaType.String,
                        type: { type: SchemaType.Any }
                    };
                }
                else if (prop === '[[Number]]') {
                    newSchema.indexSignature = newSchema.indexSignature || {
                        keyType: SchemaType.Number,
                        type: { type: SchemaType.Any }
                    };
                }
                else if (!schema.properties.find(function (v) { return v.name === prop; })) {
                    newSchema.properties.push({
                        id: -1,
                        name: prop,
                        optional: true,
                        type: {
                            type: SchemaType.Any
                        }
                    });
                }
            };
            for (var _i = 0, unionProperties_1 = unionProperties; _i < unionProperties_1.length; _i++) {
                var prop = unionProperties_1[_i];
                _loop_1(prop);
            }
            return newSchema;
        };
        /**
         * 将interface及其引用转换为展平的schema
         */
        ProtoHelper.prototype.getFlatInterfaceSchema = function (schema) {
            var uuid = this._getSchemaUuid(schema);
            // from cache
            if (this._flatInterfaceSchemaCache[uuid]) {
                return this._flatInterfaceSchemaCache[uuid];
            }
            if (this.isTypeReference(schema)) {
                var parsed = this.parseReference(schema);
                if (parsed.type !== SchemaType.Interface) {
                    throw new Error("Cannot flatten non interface type: ".concat(parsed.type));
                }
                this._flatInterfaceSchemaCache[uuid] = this.getFlatInterfaceSchema(parsed);
            }
            else if (schema.type === SchemaType.Interface) {
                this._flatInterfaceSchemaCache[uuid] = this._flattenInterface(schema);
            }
            else if (this.isMappedType(schema)) {
                this._flatInterfaceSchemaCache[uuid] = this._flattenMappedType(schema);
            }
            else {
                // @ts-expect-error
                throw new Error('Invalid interface type: ' + schema.type);
            }
            return this._flatInterfaceSchemaCache[uuid];
        };
        /**
         * 展平interface
         */
        ProtoHelper.prototype._flattenInterface = function (schema) {
            var properties = {};
            var indexSignature;
            // 自身定义的properties和indexSignature优先级最高
            if (schema.properties) {
                for (var _i = 0, _a = schema.properties; _i < _a.length; _i++) {
                    var prop = _a[_i];
                    properties[prop.name] = {
                        optional: prop.optional,
                        type: prop.type
                    };
                }
            }
            if (schema.indexSignature) {
                indexSignature = schema.indexSignature;
            }
            // extends的优先级次之，补全没有定义的字段
            if (schema.extends) {
                for (var _b = 0, _c = schema.extends; _b < _c.length; _b++) {
                    var extend = _c[_b];
                    // 解引用
                    var parsedExtRef = this.parseReference(extend.type);
                    if (this.isMappedType(parsedExtRef)) {
                        parsedExtRef = this._flattenMappedType(parsedExtRef);
                    }
                    if (!this.isInterface(parsedExtRef)) {
                        throw new Error('SchemaError: extends must from interface but from ' + parsedExtRef.type);
                    }
                    // 递归展平extends
                    var flatenExtendsSchema = this.getFlatInterfaceSchema(parsedExtRef);
                    // properties
                    if (flatenExtendsSchema.properties) {
                        for (var _d = 0, _e = flatenExtendsSchema.properties; _d < _e.length; _d++) {
                            var prop = _e[_d];
                            if (!properties[prop.name]) {
                                properties[prop.name] = {
                                    optional: prop.optional,
                                    type: prop.type
                                };
                            }
                        }
                    }
                    // indexSignature
                    if (flatenExtendsSchema.indexSignature && !indexSignature) {
                        indexSignature = flatenExtendsSchema.indexSignature;
                    }
                }
            }
            return {
                type: SchemaType.Interface,
                properties: Object.entries(properties).map(function (v, i) { return ({
                    id: i,
                    name: v[0],
                    optional: v[1].optional,
                    type: v[1].type
                }); }),
                indexSignature: indexSignature
            };
        };
        /** 将MappedTypeSchema转换为展平的Interface
         */
        ProtoHelper.prototype._flattenMappedType = function (schema) {
            // target 解引用
            var target;
            if (this.isTypeReference(schema.target)) {
                var parsed = this.parseReference(schema.target);
                target = parsed;
            }
            else {
                target = schema.target;
            }
            var flatTarget;
            // 内层仍然为MappedType 递归之
            if (target.type === SchemaType.Pick || target.type === SchemaType.Partial || target.type === SchemaType.Omit || target.type === SchemaType.Overwrite) {
                flatTarget = this._flattenMappedType(target);
            }
            else if (target.type === SchemaType.Interface) {
                flatTarget = this._flattenInterface(target);
            }
            else {
                throw new Error("Invalid target.type: ".concat(target.type));
            }
            // 开始执行Mapped逻辑
            if (schema.type === SchemaType.Pick) {
                var properties = [];
                var _loop_2 = function (key) {
                    var propItem = flatTarget.properties.find(function (v) { return v.name === key; });
                    if (propItem) {
                        properties.push({
                            id: properties.length,
                            name: key,
                            optional: propItem.optional,
                            type: propItem.type
                        });
                    }
                    else if (flatTarget.indexSignature) {
                        properties.push({
                            id: properties.length,
                            name: key,
                            type: flatTarget.indexSignature.type
                        });
                    }
                };
                for (var _i = 0, _a = schema.keys; _i < _a.length; _i++) {
                    var key = _a[_i];
                    _loop_2(key);
                }
                return {
                    type: SchemaType.Interface,
                    properties: properties
                };
            }
            else if (schema.type === SchemaType.Partial) {
                for (var _b = 0, _c = flatTarget.properties; _b < _c.length; _b++) {
                    var v = _c[_b];
                    v.optional = true;
                }
                return flatTarget;
            }
            else if (schema.type === SchemaType.Omit) {
                var _loop_3 = function (key) {
                    flatTarget.properties.removeOne(function (v) { return v.name === key; });
                };
                for (var _d = 0, _e = schema.keys; _d < _e.length; _d++) {
                    var key = _e[_d];
                    _loop_3(key);
                }
                return flatTarget;
            }
            else if (schema.type === SchemaType.Overwrite) {
                var overwrite = this.getFlatInterfaceSchema(schema.overwrite);
                if (overwrite.indexSignature) {
                    flatTarget.indexSignature = overwrite.indexSignature;
                }
                var _loop_4 = function (prop) {
                    flatTarget.properties.removeOne(function (v) { return v.name === prop.name; });
                    flatTarget.properties.push(prop);
                };
                for (var _f = 0, _g = overwrite.properties; _f < _g.length; _f++) {
                    var prop = _g[_f];
                    _loop_4(prop);
                }
                return flatTarget;
            }
            else {
                throw new Error("Unknown type: ".concat(schema.type));
            }
        };
        ProtoHelper.prototype.parseMappedType = function (schema) {
            var cache = this._parseMappedTypeCache.get(schema);
            if (cache) {
                return cache;
            }
            // 解嵌套，例如：Pick<Pick<Omit, XXX, 'a'|'b'>>>
            var parents = [];
            var child = schema;
            do {
                parents.push(child);
                child = this.parseReference(child.target);
            } while (this.isMappedType(child));
            // 最内层是 interface，直接返回（validator 会验证 key 匹配）
            if (child.type === SchemaType.Interface) {
                this._parseMappedTypeCache.set(schema, child);
                return child;
            }
            // PickOmit<A|B> === PickOmit<A> | PickOmit<B>
            else if (child.type === SchemaType.Union || child.type === SchemaType.Intersection) {
                var newSchema = {
                    type: child.type,
                    members: child.members.map(function (v) {
                        // 从里面往外装
                        var type = v.type;
                        for (var i = parents.length - 1; i > -1; --i) {
                            var parent_1 = parents[i];
                            type = __assign(__assign({}, parent_1), { target: type });
                        }
                        return {
                            id: v.id,
                            type: type
                        };
                    })
                };
                this._parseMappedTypeCache.set(schema, newSchema);
                return newSchema;
            }
            else {
                throw new Error("Unsupported pattern ".concat(schema.type, "<").concat(child.type, ">"));
            }
        };
        return ProtoHelper;
    }());

    var _a;
    /** @internal */
    var ErrorType;
    (function (ErrorType) {
        ErrorType["TypeError"] = "TypeError";
        ErrorType["InvalidScalarType"] = "InvalidScalarType";
        ErrorType["TupleOverLength"] = "TupleOverLength";
        ErrorType["InvalidEnumValue"] = "InvalidEnumValue";
        ErrorType["InvalidLiteralValue"] = "InvalidLiteralValue";
        ErrorType["MissingRequiredProperty"] = "MissingRequiredProperty";
        ErrorType["ExcessProperty"] = "ExcessProperty";
        ErrorType["InvalidNumberKey"] = "InvalidNumberKey";
        ErrorType["UnionTypesNotMatch"] = "UnionTypesNotMatch";
        ErrorType["UnionMembersNotMatch"] = "UnionMembersNotMatch";
        ErrorType["CustomError"] = "CustomError";
    })(ErrorType || (ErrorType = {}));
    /** @internal */
    var ErrorMsg = (_a = {},
        _a[ErrorType.TypeError] = function (expect, actual) { return "Expected type to be `".concat(expect, "`, actually `").concat(actual, "`."); },
        _a[ErrorType.InvalidScalarType] = function (value, scalarType) { return "`".concat(value, "` is not a valid `").concat(scalarType, "`."); },
        _a[ErrorType.TupleOverLength] = function (valueLength, schemaLength) { return "Value has ".concat(valueLength, " elements but schema allows only ").concat(schemaLength, "."); },
        _a[ErrorType.InvalidEnumValue] = function (value) { return "`".concat(value, "` is not a valid enum member."); },
        _a[ErrorType.InvalidLiteralValue] = function (expected, actual) { return "Expected to equals `".concat(stringify(expected), "`, actually `").concat(stringify(actual), "`"); },
        _a[ErrorType.MissingRequiredProperty] = function (propName) { return "Missing required property `".concat(propName, "`."); },
        _a[ErrorType.ExcessProperty] = function (propName) { return "Excess property `".concat(propName, "` should not exists."); },
        _a[ErrorType.InvalidNumberKey] = function (key) { return "`".concat(key, "` is not a valid key, the key here should be a `number`."); },
        // Union
        _a[ErrorType.UnionTypesNotMatch] = function (value, types) { return "`".concat(stringify(value), "` is not matched to `").concat(types.join(' | '), "`"); },
        _a[ErrorType.UnionMembersNotMatch] = function (memberErrors) { return "No union member matched, detail:\n".concat(memberErrors.map(function (v, i) { return "  <".concat(i, "> ").concat(v.errMsg); }).join('\n')); },
        _a[ErrorType.CustomError] = function (errMsg) { return errMsg; },
        _a);
    /** @internal */
    function stringify(value) {
        if (typeof value === 'string') {
            var output = JSON.stringify(value);
            return "'" + output.substr(1, output.length - 2) + "'";
        }
        return JSON.stringify(value);
    }

    /** @internal */
    var ValidateResultError = /** @class */ (function () {
        function ValidateResultError(error) {
            this.isSucc = false;
            this.error = error;
        }
        Object.defineProperty(ValidateResultError.prototype, "errMsg", {
            get: function () {
                return ValidateResultError.getErrMsg(this.error);
            },
            enumerable: false,
            configurable: true
        });
        ValidateResultError.getErrMsg = function (error) {
            var _a;
            var errMsg = ErrorMsg[error.type].apply(ErrorMsg, error.params);
            if ((_a = error.inner) === null || _a === void 0 ? void 0 : _a.property.length) {
                return "Property `".concat(error.inner.property.join('.'), "`: ").concat(errMsg);
            }
            else {
                return errMsg;
            }
        };
        return ValidateResultError;
    }());
    /** @internal  */
    var ValidateResultUtil = /** @class */ (function () {
        function ValidateResultUtil() {
        }
        ValidateResultUtil.error = function (type) {
            var params = [];
            for (var _i = 1; _i < arguments.length; _i++) {
                params[_i - 1] = arguments[_i];
            }
            return new ValidateResultError({
                type: type,
                params: params
            });
        };
        ValidateResultUtil.innerError = function (property, value, schema, error) {
            var _a;
            if (error.error.inner) {
                if (typeof property === 'string') {
                    error.error.inner.property.unshift(property);
                }
                else {
                    (_a = error.error.inner.property).unshift.apply(_a, property);
                }
            }
            else {
                error.error.inner = {
                    property: typeof property === 'string' ? [property] : property,
                    value: value,
                    schema: schema
                };
            }
            return error;
        };
        ValidateResultUtil.succ = { isSucc: true };
        return ValidateResultUtil;
    }());

    var typedArrays = {
        Int8Array: Int8Array,
        Int16Array: Int16Array,
        Int32Array: Int32Array,
        BigInt64Array: typeof BigInt64Array !== 'undefined' ? BigInt64Array : undefined,
        Uint8Array: Uint8Array,
        Uint16Array: Uint16Array,
        Uint32Array: Uint32Array,
        BigUint64Array: typeof BigUint64Array !== 'undefined' ? BigUint64Array : undefined,
        Float32Array: Float32Array,
        Float64Array: Float64Array
    };
    /**
     * TSBuffer Schema Validator
     * @public
     */
    var TSBufferValidator = /** @class */ (function () {
        function TSBufferValidator(proto, options) {
            /**
             * Default options
             */
            this.options = {
                excessPropertyChecks: true,
                strictNullChecks: false,
                cloneProto: true
            };
            if (options) {
                this.options = __assign(__assign({}, this.options), options);
            }
            this.proto = this.options.cloneProto ? Object.merge({}, proto) : proto;
            this.protoHelper = new ProtoHelper(this.proto);
        }
        /**
         * Validate whether the value is valid to the schema
         * @param value - Value to be validated.
         * @param schemaId - Schema or schema ID.
         * For example, the schema ID for type `Test` in `a/b.ts` may be `a/b/Test`.
         */
        TSBufferValidator.prototype.validate = function (value, schemaOrId, options) {
            var _a, _b;
            var schema;
            var schemaId;
            // Get schema
            if (typeof schemaOrId === 'string') {
                schemaId = schemaOrId;
                schema = this.proto[schemaId];
                if (!schema) {
                    throw new Error("Cannot find schema: ".concat(schemaId));
                }
            }
            else {
                schema = schemaOrId;
            }
            // Merge default options
            return this._validate(value, schema, __assign(__assign({}, options), { excessPropertyChecks: (_a = options === null || options === void 0 ? void 0 : options.excessPropertyChecks) !== null && _a !== void 0 ? _a : this.options.excessPropertyChecks, strictNullChecks: (_b = options === null || options === void 0 ? void 0 : options.strictNullChecks) !== null && _b !== void 0 ? _b : this.options.strictNullChecks }));
        };
        TSBufferValidator.prototype._validate = function (value, schema, options) {
            var _a;
            var vRes;
            // Validate
            switch (schema.type) {
                case SchemaType.Boolean:
                    vRes = this._validateBooleanType(value, schema);
                    break;
                case SchemaType.Number:
                    vRes = this._validateNumberType(value, schema);
                    break;
                case SchemaType.String:
                    vRes = this._validateStringType(value, schema);
                    break;
                case SchemaType.Array:
                    vRes = this._validateArrayType(value, schema, options);
                    break;
                case SchemaType.Tuple:
                    vRes = this._validateTupleType(value, schema, options);
                    break;
                case SchemaType.Enum:
                    vRes = this._validateEnumType(value, schema);
                    break;
                case SchemaType.Any:
                    vRes = this._validateAnyType(value);
                    break;
                case SchemaType.Literal:
                    vRes = this._validateLiteralType(value, schema, (_a = options === null || options === void 0 ? void 0 : options.strictNullChecks) !== null && _a !== void 0 ? _a : this.options.strictNullChecks);
                    break;
                case SchemaType.Object:
                    vRes = this._validateObjectType(value, schema);
                    break;
                case SchemaType.Interface:
                    vRes = this._validateInterfaceType(value, schema, options);
                    break;
                case SchemaType.Buffer:
                    vRes = this._validateBufferType(value, schema);
                    break;
                case SchemaType.IndexedAccess:
                case SchemaType.Reference:
                case SchemaType.Keyof:
                    vRes = this._validateReferenceType(value, schema, options);
                    break;
                case SchemaType.Union:
                    vRes = this._validateUnionType(value, schema, options);
                    break;
                case SchemaType.Intersection:
                    vRes = this._validateIntersectionType(value, schema, options);
                    break;
                case SchemaType.Pick:
                case SchemaType.Omit:
                case SchemaType.Partial:
                case SchemaType.Overwrite:
                    vRes = this._validateMappedType(value, schema, options);
                    break;
                case SchemaType.Date:
                    vRes = this._validateDateType(value);
                    break;
                case SchemaType.NonNullable:
                    vRes = this._validateNonNullableType(value, schema, options);
                    break;
                case SchemaType.Custom:
                    var res = schema.validate(value);
                    vRes = res.isSucc ? ValidateResultUtil.succ : ValidateResultUtil.error(ErrorType.CustomError, res.errMsg);
                    break;
                // 错误的type
                default:
                    // @ts-expect-error
                    throw new Error("Unsupported schema type: ".concat(schema.type));
            }
            // prune
            if (options === null || options === void 0 ? void 0 : options.prune) {
                // don't need prune, return original value
                if (options.prune.output === undefined) {
                    options.prune.output = value;
                }
                // output to parent
                if (options.prune.parent) {
                    options.prune.parent.value[options.prune.parent.key] = options.prune.output;
                }
            }
            return vRes;
        };
        /**
         * 修剪 Object，移除 Schema 中未定义的 Key
         * 需要确保 value 类型合法
         * @param value - value to be validated
         * @param schemaOrId -Schema or schema ID.
         * @returns Validate result and pruned value. if validate failed, `pruneOutput` would be undefined.
         */
        TSBufferValidator.prototype.prune = function (value, schemaOrId, options) {
            var _a;
            var schema = typeof schemaOrId === 'string' ? this.proto[schemaOrId] : schemaOrId;
            if (!schema) {
                throw new Error('Cannot find schema: ' + schemaOrId);
            }
            var prune = {};
            var vRes = this._validate(value, schema, __assign(__assign({}, options), { prune: prune, excessPropertyChecks: false, strictNullChecks: (_a = options === null || options === void 0 ? void 0 : options.strictNullChecks) !== null && _a !== void 0 ? _a : this.options.strictNullChecks }));
            if (vRes.isSucc) {
                vRes.pruneOutput = prune.output;
            }
            return vRes;
        };
        TSBufferValidator.prototype._validateBooleanType = function (value, schema) {
            var type = this._getTypeof(value);
            if (type === 'boolean') {
                return ValidateResultUtil.succ;
            }
            else {
                return ValidateResultUtil.error(ErrorType.TypeError, 'boolean', type);
            }
        };
        TSBufferValidator.prototype._validateNumberType = function (value, schema) {
            // 默认为double
            var scalarType = schema.scalarType || 'double';
            // Wrong Type
            var type = this._getTypeof(value);
            var rightType = scalarType.indexOf('big') > -1 ? 'bigint' : 'number';
            if (type !== rightType) {
                return ValidateResultUtil.error(ErrorType.TypeError, rightType, type);
            }
            // scalarType类型检测
            // 整形却为小数
            if (scalarType !== 'double' && type === 'number' && !Number.isInteger(value)) {
                return ValidateResultUtil.error(ErrorType.InvalidScalarType, value, scalarType);
            }
            // 无符号整形却为负数
            if (scalarType.indexOf('uint') > -1 && value < 0) {
                return ValidateResultUtil.error(ErrorType.InvalidScalarType, value, scalarType);
            }
            return ValidateResultUtil.succ;
        };
        TSBufferValidator.prototype._validateStringType = function (value, schema) {
            var type = this._getTypeof(value);
            return type === 'string' ? ValidateResultUtil.succ : ValidateResultUtil.error(ErrorType.TypeError, 'string', type);
        };
        TSBufferValidator.prototype._validateArrayType = function (value, schema, options) {
            // is Array type
            var type = this._getTypeof(value);
            if (type !== SchemaType.Array) {
                return ValidateResultUtil.error(ErrorType.TypeError, SchemaType.Array, type);
            }
            // prune output
            var prune = options.prune;
            if (prune) {
                prune.output = Array.from({ length: value.length });
            }
            // validate elementType
            for (var i = 0; i < value.length; ++i) {
                var elemValidateResult = this._validate(value[i], schema.elementType, __assign(__assign({}, options), { prune: (prune === null || prune === void 0 ? void 0 : prune.output) ? {
                        parent: {
                            value: prune.output,
                            key: i
                        }
                    } : undefined }));
                if (!elemValidateResult.isSucc) {
                    return ValidateResultUtil.innerError('' + i, value[i], schema.elementType, elemValidateResult);
                }
            }
            return ValidateResultUtil.succ;
        };
        TSBufferValidator.prototype._validateTupleType = function (value, schema, options) {
            // is Array type
            var type = this._getTypeof(value);
            if (type !== SchemaType.Array) {
                return ValidateResultUtil.error(ErrorType.TypeError, SchemaType.Array, type);
            }
            var prune = options.prune;
            // validate length
            // excessPropertyChecks 与 prune互斥
            if (!prune && options.excessPropertyChecks && value.length > schema.elementTypes.length) {
                return ValidateResultUtil.error(ErrorType.TupleOverLength, value.length, schema.elementTypes.length);
            }
            // prune output
            if (prune) {
                prune.output = Array.from({ length: Math.min(value.length, schema.elementTypes.length) });
            }
            // validate elementType
            for (var i = 0; i < schema.elementTypes.length; ++i) {
                // MissingRequiredProperty: NotOptional && is undefined
                if (value[i] === undefined || value[i] === null && !options.strictNullChecks) {
                    var canBeNull = this._canBeNull(schema.elementTypes[i]);
                    var canBeUndefined = schema.optionalStartIndex !== undefined && i >= schema.optionalStartIndex || this._canBeUndefined(schema.elementTypes[i]);
                    var isOptional = canBeUndefined || !options.strictNullChecks && canBeNull;
                    // skip undefined property
                    if (isOptional) {
                        // Prune null & undefined->null
                        if (prune === null || prune === void 0 ? void 0 : prune.output) {
                            if (value[i] === null && canBeNull
                                || value[i] === undefined && !canBeUndefined && canBeNull) {
                                prune.output[i] = null;
                            }
                        }
                        continue;
                    }
                    else {
                        return ValidateResultUtil.error(ErrorType.MissingRequiredProperty, i);
                    }
                }
                // element type check
                var elemValidateResult = this._validate(value[i], schema.elementTypes[i], {
                    prune: (prune === null || prune === void 0 ? void 0 : prune.output) ? {
                        parent: {
                            value: prune.output,
                            key: i
                        }
                    } : undefined,
                    strictNullChecks: options.strictNullChecks,
                    excessPropertyChecks: options.excessPropertyChecks
                });
                if (!elemValidateResult.isSucc) {
                    return ValidateResultUtil.innerError('' + i, value[i], schema.elementTypes[i], elemValidateResult);
                }
            }
            return ValidateResultUtil.succ;
        };
        TSBufferValidator.prototype._canBeUndefined = function (schema) {
            var _this = this;
            if (schema.type === SchemaType.Union) {
                return schema.members.some(function (v) { return _this._canBeUndefined(v.type); });
            }
            if (schema.type === SchemaType.Literal && schema.literal === undefined) {
                return true;
            }
            return false;
        };
        TSBufferValidator.prototype._canBeNull = function (schema) {
            var _this = this;
            if (schema.type === SchemaType.Union) {
                return schema.members.some(function (v) { return _this._canBeNull(v.type); });
            }
            if (schema.type === SchemaType.Literal && schema.literal === null) {
                return true;
            }
            return false;
        };
        TSBufferValidator.prototype._validateEnumType = function (value, schema) {
            // must be string or number
            var type = this._getTypeof(value);
            if (type !== 'string' && type !== 'number') {
                return ValidateResultUtil.error(ErrorType.TypeError, 'string | number', type);
            }
            // 有值与预设相同
            if (schema.members.some(function (v) { return v.value === value; })) {
                return ValidateResultUtil.succ;
            }
            else {
                return ValidateResultUtil.error(ErrorType.InvalidEnumValue, value);
            }
        };
        TSBufferValidator.prototype._validateAnyType = function (value) {
            return ValidateResultUtil.succ;
        };
        TSBufferValidator.prototype._validateLiteralType = function (value, schema, strictNullChecks) {
            // 非strictNullChecks严格模式，null undefined同等对待
            if (!strictNullChecks && (schema.literal === null || schema.literal === undefined)) {
                return value === null || value === undefined ?
                    ValidateResultUtil.succ
                    : ValidateResultUtil.error(ErrorType.InvalidLiteralValue, schema.literal, value);
            }
            return value === schema.literal ?
                ValidateResultUtil.succ
                : ValidateResultUtil.error(ErrorType.InvalidLiteralValue, schema.literal, value);
        };
        TSBufferValidator.prototype._validateObjectType = function (value, schema) {
            var type = this._getTypeof(value);
            return type === 'Object' || type === 'Array' ? ValidateResultUtil.succ : ValidateResultUtil.error(ErrorType.TypeError, 'Object', type);
        };
        TSBufferValidator.prototype._validateInterfaceType = function (value, schema, options) {
            var type = this._getTypeof(value);
            if (type !== 'Object') {
                return ValidateResultUtil.error(ErrorType.TypeError, 'Object', type);
            }
            // 先展平
            var flatSchema = this.protoHelper.getFlatInterfaceSchema(schema);
            // From union or intersecton type
            if (options.unionProperties) {
                flatSchema = this.protoHelper.applyUnionProperties(flatSchema, options.unionProperties);
            }
            return this._validateFlatInterface(value, flatSchema, options);
        };
        TSBufferValidator.prototype._validateMappedType = function (value, schema, options) {
            var parsed = this.protoHelper.parseMappedType(schema);
            if (parsed.type === SchemaType.Interface) {
                return this._validateInterfaceType(value, schema, options);
            }
            else if (parsed.type === SchemaType.Union) {
                return this._validateUnionType(value, parsed, options);
            }
            else if (parsed.type === SchemaType.Intersection) {
                return this._validateIntersectionType(value, parsed, options);
            }
            // @ts-expect-error
            throw new Error("Invalid ".concat(schema.type, " target type: ").concat(parsed.type));
        };
        TSBufferValidator.prototype._validateFlatInterface = function (value, schema, options) {
            // interfaceSignature强制了key必须是数字的情况
            if (schema.indexSignature && schema.indexSignature.keyType === SchemaType.Number) {
                for (var key in value) {
                    if (!this._isNumberKey(key)) {
                        return ValidateResultUtil.error(ErrorType.InvalidNumberKey, key);
                    }
                }
            }
            var prune = options.prune;
            if (prune) {
                prune.output = {};
            }
            // Excess property check (与prune互斥)
            if (!prune && options.excessPropertyChecks && !schema.indexSignature) {
                var validProperties_1 = schema.properties.map(function (v) { return v.name; });
                var firstExcessProperty = Object.keys(value).find(function (v) { return validProperties_1.indexOf(v) === -1; });
                if (firstExcessProperty) {
                    return ValidateResultUtil.error(ErrorType.ExcessProperty, firstExcessProperty);
                }
            }
            // 校验properties
            if (schema.properties) {
                for (var _i = 0, _a = schema.properties; _i < _a.length; _i++) {
                    var property = _a[_i];
                    // MissingRequiredProperty: is undefined && !isOptional
                    if (value[property.name] === undefined || value[property.name] === null && !options.strictNullChecks) {
                        var canBeNull = this._canBeNull(property.type);
                        var canBeUndefined = property.optional || this._canBeUndefined(property.type);
                        var isOptional = canBeUndefined || !options.strictNullChecks && canBeNull;
                        // skip undefined optional property
                        if (isOptional) {
                            // Prune null & undefined->null
                            if (prune === null || prune === void 0 ? void 0 : prune.output) {
                                if (value[property.name] === null && canBeNull
                                    || value[property.name] === undefined && !canBeUndefined && canBeNull) {
                                    prune.output[property.name] = null;
                                }
                            }
                            continue;
                        }
                        else {
                            return ValidateResultUtil.error(ErrorType.MissingRequiredProperty, property.name);
                        }
                    }
                    // property本身验证
                    var vRes = this._validate(value[property.name], property.type, {
                        prune: (prune === null || prune === void 0 ? void 0 : prune.output) && property.id > -1 ? {
                            parent: {
                                value: prune.output,
                                key: property.name
                            }
                        } : undefined,
                        strictNullChecks: options.strictNullChecks,
                        excessPropertyChecks: options.excessPropertyChecks
                    });
                    if (!vRes.isSucc) {
                        return ValidateResultUtil.innerError(property.name, value[property.name], property.type, vRes);
                    }
                }
            }
            // 检测indexSignature
            if (schema.indexSignature) {
                for (var key in value) {
                    // only prune is (property is pruned already)
                    // let memberPrune: ValidatePruneOptions | undefined = schema.properties.some(v => v.name === key) ? undefined : {};
                    // validate each field
                    var vRes = this._validate(value[key], schema.indexSignature.type, {
                        prune: (prune === null || prune === void 0 ? void 0 : prune.output) ? {
                            parent: {
                                value: prune.output,
                                key: key
                            }
                        } : undefined,
                        strictNullChecks: options.strictNullChecks,
                        excessPropertyChecks: options.excessPropertyChecks
                    });
                    if (!vRes.isSucc) {
                        return ValidateResultUtil.innerError(key, value[key], schema.indexSignature.type, vRes);
                    }
                }
            }
            return ValidateResultUtil.succ;
        };
        TSBufferValidator.prototype._validateBufferType = function (value, schema) {
            var _a, _b;
            var type = this._getTypeof(value);
            if (type !== 'Object') {
                return ValidateResultUtil.error(ErrorType.TypeError, schema.arrayType || 'ArrayBuffer', type);
            }
            else if (schema.arrayType) {
                var typeArrayClass = typedArrays[schema.arrayType];
                if (!typeArrayClass) {
                    throw new Error("Error TypedArray type: ".concat(schema.arrayType));
                }
                return value instanceof typeArrayClass ? ValidateResultUtil.succ : ValidateResultUtil.error(ErrorType.TypeError, schema.arrayType, (_a = value === null || value === void 0 ? void 0 : value.constructor) === null || _a === void 0 ? void 0 : _a.name);
            }
            else {
                return value instanceof ArrayBuffer ? ValidateResultUtil.succ : ValidateResultUtil.error(ErrorType.TypeError, 'ArrayBuffer', (_b = value === null || value === void 0 ? void 0 : value.constructor) === null || _b === void 0 ? void 0 : _b.name);
            }
        };
        TSBufferValidator.prototype._validateReferenceType = function (value, schema, options) {
            return this._validate(value, this.protoHelper.parseReference(schema), options);
        };
        TSBufferValidator.prototype._validateUnionType = function (value, schema, options) {
            var _this = this;
            options.unionProperties = options.unionProperties || this.protoHelper.getUnionProperties(schema);
            var isObjectPrune = false;
            var prune = options.prune;
            if (prune && value && Object.getPrototypeOf(value) === Object.prototype) {
                isObjectPrune = true;
                prune.output = {};
            }
            // 有一成功则成功
            var isSomeSucc = false;
            var memberErrors = [];
            for (var i = 0; i < schema.members.length; ++i) {
                var member = schema.members[i];
                var memberType = this.protoHelper.isTypeReference(member.type) ? this.protoHelper.parseReference(member.type) : member.type;
                var memberPrune = prune ? {} : undefined;
                var vRes = this._validate(value, memberType, __assign(__assign({}, options), { prune: memberPrune }));
                if (vRes.isSucc) {
                    isSomeSucc = true;
                    // if prune object: must prune all members
                    if (isObjectPrune) {
                        prune.output = __assign(__assign({}, prune.output), memberPrune.output);
                    }
                    // not prune object: stop checking after 1st member matched
                    else {
                        break;
                    }
                }
                else {
                    memberErrors.push(vRes);
                }
            }
            // 有一成功则成功;
            if (isSomeSucc) {
                return ValidateResultUtil.succ;
            }
            // 全部失败，则失败
            else {
                // All member error is the same, return the first
                var msg0_1 = memberErrors[0].errMsg;
                if (memberErrors.every(function (v) { return v.errMsg === msg0_1; })) {
                    return memberErrors[0];
                }
                // mutual exclusion: return the only one
                var nonLiteralErrors = memberErrors.filter(function (v) { return v.error.type !== ErrorType.InvalidLiteralValue; });
                if (nonLiteralErrors.length === 1) {
                    return nonLiteralErrors[0];
                }
                // All member error without inner: show simple msg
                if (memberErrors.every(function (v) { return !v.error.inner && (v.error.type === ErrorType.TypeError || v.error.type === ErrorType.InvalidLiteralValue); })) {
                    var valueType = this._getTypeof(value);
                    var expectedTypes = memberErrors.map(function (v) { return v.error.type === ErrorType.TypeError ? v.error.params[0] : _this._getTypeof(v.error.params[0]); }).distinct();
                    // Expected type A|B|C, actually type D
                    if (expectedTypes.indexOf(valueType) === -1) {
                        return ValidateResultUtil.error(ErrorType.TypeError, expectedTypes.join(' | '), this._getTypeof(value));
                    }
                    // `'D'` is not matched to `'A'|'B'|'C'`
                    if (valueType !== 'Object' && valueType !== SchemaType.Array) {
                        var types = memberErrors.map(function (v) { return v.error.type === ErrorType.TypeError ? v.error.params[0] : stringify(v.error.params[0]); }).distinct();
                        return ValidateResultUtil.error(ErrorType.UnionTypesNotMatch, value, types);
                    }
                }
                // other errors
                return ValidateResultUtil.error(ErrorType.UnionMembersNotMatch, memberErrors);
            }
        };
        TSBufferValidator.prototype._validateIntersectionType = function (value, schema, options) {
            options.unionProperties = options.unionProperties || this.protoHelper.getUnionProperties(schema);
            var isObjectPrune = false;
            var prune = options.prune;
            if (prune && value && Object.getPrototypeOf(value) === Object.prototype) {
                prune.output = {};
                isObjectPrune = true;
            }
            // 有一失败则失败
            for (var i = 0, len = schema.members.length; i < len; ++i) {
                // 验证member
                var memberType = schema.members[i].type;
                memberType = this.protoHelper.isTypeReference(memberType) ? this.protoHelper.parseReference(memberType) : memberType;
                var memberPrune = prune ? {} : undefined;
                var vRes = this._validate(value, memberType, __assign(__assign({}, options), { prune: memberPrune }));
                // 有一失败则失败
                if (!vRes.isSucc) {
                    return vRes;
                }
                if (isObjectPrune) {
                    prune.output = __assign(__assign({}, prune.output), memberPrune.output);
                }
            }
            // 全成功则成功
            return ValidateResultUtil.succ;
        };
        TSBufferValidator.prototype._validateDateType = function (value) {
            if (value instanceof Date) {
                return ValidateResultUtil.succ;
            }
            else {
                return ValidateResultUtil.error(ErrorType.TypeError, 'Date', this._getTypeof(value));
            }
        };
        TSBufferValidator.prototype._validateNonNullableType = function (value, schema, options) {
            var type = this._getTypeof(value);
            if ((type === 'null' || type === 'undefined') && schema.target.type !== 'Any') {
                return ValidateResultUtil.error(ErrorType.TypeError, 'NonNullable', type);
            }
            return this._validate(value, schema.target, options);
        };
        TSBufferValidator.prototype._isNumberKey = function (key) {
            var int = parseInt(key);
            return !(isNaN(int) || ('' + int) !== key);
        };
        TSBufferValidator.prototype._getTypeof = function (value) {
            var type = typeof value;
            if (type === 'object') {
                if (value === null) {
                    return 'null';
                }
                else if (Array.isArray(value)) {
                    return SchemaType.Array;
                }
                else {
                    return 'Object';
                }
            }
            return type;
        };
        return TSBufferValidator;
    }());

    /*!
     * TSBuffer v2.2.9
     * -----------------------------------------
     * MIT LICENSE
     * KingWorks (C) Copyright 2024
     * https://github.com/k8w/tsbuffer
     */

    var Base64Util = /** @class */ (function () {
        function Base64Util() {
        }
        Base64Util.bufferToBase64 = function (buf) {
            if (typeof Buffer !== 'undefined') {
                return Buffer.from(buf).toString('base64');
            }
            var base64 = '';
            var len = buf.length;
            for (var i = 0; i < len; i += 3) {
                base64 += base64Chars[buf[i] >> 2];
                base64 += base64Chars[((buf[i] & 3) << 4) | (buf[i + 1] >> 4)];
                base64 += base64Chars[((buf[i + 1] & 15) << 2) | (buf[i + 2] >> 6)];
                base64 += base64Chars[buf[i + 2] & 63];
            }
            if (len % 3 === 2) {
                base64 = base64.substring(0, base64.length - 1) + '=';
            }
            else if (len % 3 === 1) {
                base64 = base64.substring(0, base64.length - 2) + '==';
            }
            return base64;
        };
        Base64Util.base64ToBuffer = function (base64) {
            if (typeof Buffer !== 'undefined') {
                return new Uint8Array(Buffer.from(base64, 'base64'));
            }
            var bufferLength = base64.length * 0.75, len = base64.length, p = 0;
            var encoded1, encoded2, encoded3, encoded4;
            if (base64[base64.length - 1] === '=') {
                bufferLength--;
                if (base64[base64.length - 2] === '=') {
                    bufferLength--;
                }
            }
            var buf = new Uint8Array(bufferLength);
            for (var i = 0; i < len; i += 4) {
                encoded1 = lookup[base64.charCodeAt(i)];
                encoded2 = lookup[base64.charCodeAt(i + 1)];
                encoded3 = lookup[base64.charCodeAt(i + 2)];
                encoded4 = lookup[base64.charCodeAt(i + 3)];
                buf[p++] = (encoded1 << 2) | (encoded2 >> 4);
                buf[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2);
                buf[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63);
            }
            return buf;
        };
        return Base64Util;
    }());
    /*base64*/
    var base64Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    // Use a lookup table to find the index.
    var lookup = typeof Uint8Array === 'undefined' ? [] : new Uint8Array(256);
    for (var i = 0; i < base64Chars.length; i++) {
        lookup[base64Chars.charCodeAt(i)] = i;
    }
    /*end*/

    var CoderUtil = /** @class */ (function () {
        function CoderUtil() {
        }
        CoderUtil.isJsonCompatible = function (schema, type, protoHelper) {
            var _this = this;
            var schemaInfo = schema;
            var key = type === 'encode' ? 'isJsonEncodable' : 'isJsonDecodable';
            if (schemaInfo[key] === undefined) {
                // Just for avoding circular recursive, the value should be overwriten below
                schemaInfo[key] = true;
                switch (schema.type) {
                    case SchemaType.Array:
                        schemaInfo[key] = this.isJsonCompatible(schema.elementType, type, protoHelper);
                        break;
                    case SchemaType.Tuple:
                        schemaInfo[key] = schema.elementTypes.every(function (v) { return _this.isJsonCompatible(v, type, protoHelper); });
                        break;
                    case SchemaType.Interface:
                        var flatSchema = protoHelper.getFlatInterfaceSchema(schema);
                        schemaInfo[key] = flatSchema.properties.every(function (v) { return _this.isJsonCompatible(v.type, type, protoHelper); });
                        if (flatSchema.indexSignature) {
                            schemaInfo[key] = schemaInfo[key] && this.isJsonCompatible(flatSchema.indexSignature.type, type, protoHelper);
                        }
                        break;
                    case SchemaType.IndexedAccess:
                    case SchemaType.Reference: {
                        var parsed = protoHelper.parseReference(schema);
                        schemaInfo[key] = this.isJsonCompatible(parsed, type, protoHelper);
                        break;
                    }
                    case SchemaType.Union:
                    case SchemaType.Intersection:
                        schemaInfo[key] = schema.members.every(function (v) { return _this.isJsonCompatible(v.type, type, protoHelper); });
                        break;
                    case SchemaType.NonNullable:
                        schemaInfo[key] = this.isJsonCompatible(schema.target, type, protoHelper);
                        break;
                    case SchemaType.Pick:
                    case SchemaType.Partial:
                    case SchemaType.Omit:
                    case SchemaType.Overwrite: {
                        var parsed = protoHelper.parseMappedType(schema);
                        if (parsed.type === SchemaType.Interface) {
                            var flatSchema_1 = protoHelper.getFlatInterfaceSchema(schema);
                            schemaInfo[key] = flatSchema_1.properties.every(function (v) { return _this.isJsonCompatible(v.type, type, protoHelper); });
                            if (flatSchema_1.indexSignature) {
                                schemaInfo[key] = schemaInfo[key] && this.isJsonCompatible(flatSchema_1.indexSignature.type, type, protoHelper);
                            }
                        }
                        else if (parsed.type === SchemaType.Union || parsed.type === SchemaType.Intersection) {
                            schemaInfo[key] = parsed.members.every(function (v) { return _this.isJsonCompatible(v.type, type, protoHelper); });
                        }
                        break;
                    }
                    case SchemaType.Custom:
                    case SchemaType.Date:
                    case SchemaType.Buffer:
                        schemaInfo[key] = false;
                        break;
                    default:
                        schemaInfo[key] = true;
                        break;
                }
            }
            return schemaInfo[key];
        };
        return CoderUtil;
    }());

    /** @internal */
    var IdBlockUtil = /** @class */ (function () {
        function IdBlockUtil() {
        }
        IdBlockUtil.getPayloadLengthInfo = function (parsedSchema, protoHelper) {
            switch (parsedSchema.type) {
                case SchemaType.Boolean:
                case SchemaType.Enum:
                    return { lengthType: LengthType.Varint };
                case SchemaType.Number:
                    if (!parsedSchema.scalarType || parsedSchema.scalarType.includes('64') || parsedSchema.scalarType === 'double') {
                        return { lengthType: LengthType.Bit64 };
                    }
                    else if (parsedSchema.scalarType && parsedSchema.scalarType.startsWith('big')) {
                        return { lengthType: LengthType.LengthDelimited };
                    }
                    else {
                        return { lengthType: LengthType.Varint };
                    }
                case SchemaType.Buffer:
                case SchemaType.String:
                case SchemaType.Any:
                case SchemaType.Object:
                    return { lengthType: LengthType.LengthDelimited };
                case SchemaType.Interface:
                case SchemaType.Pick:
                case SchemaType.Partial:
                case SchemaType.Omit:
                case SchemaType.Union:
                case SchemaType.Intersection:
                    return { lengthType: LengthType.IdBlock };
                case SchemaType.Array:
                case SchemaType.Overwrite:
                case SchemaType.Tuple:
                    return {
                        lengthType: LengthType.LengthDelimited,
                        needLengthPrefix: true
                    };
                case SchemaType.Literal:
                    return {
                        lengthType: LengthType.LengthDelimited,
                        needLengthPrefix: false
                    };
                case SchemaType.Date:
                    return { lengthType: LengthType.Varint };
                case SchemaType.NonNullable:
                    return this.getPayloadLengthInfo(protoHelper.parseReference(parsedSchema.target), protoHelper);
                case SchemaType.Custom:
                    return { lengthType: LengthType.LengthDelimited };
                default:
                    // @ts-expect-error
                    throw new Error("Unrecognized schema type: ".concat(parsedSchema.type));
            }
        };
        return IdBlockUtil;
    }());
    /** @internal */
    var LengthType;
    (function (LengthType) {
        LengthType[LengthType["LengthDelimited"] = 0] = "LengthDelimited";
        LengthType[LengthType["Varint"] = 1] = "Varint";
        LengthType[LengthType["Bit64"] = 2] = "Bit64";
        LengthType[LengthType["IdBlock"] = 3] = "IdBlock";
    })(LengthType || (LengthType = {}));

    /** @internal */
    var SchemaUtil = /** @class */ (function () {
        function SchemaUtil() {
        }
        /** type类型是否能编码为该literal */
        SchemaUtil.canBeLiteral = function (schema, literal) {
            var _this = this;
            if (schema.type === SchemaType.Union) {
                return schema.members.some(function (v) { return _this.canBeLiteral(v.type, literal); });
            }
            if (schema.type === SchemaType.Any) {
                return true;
            }
            if (schema.type === SchemaType.Literal && schema.literal === literal) {
                return true;
            }
            return false;
        };
        return SchemaUtil;
    }());

    var TypedArrays = {
        Int8Array: Int8Array,
        Int16Array: Int16Array,
        Int32Array: Int32Array,
        Uint8Array: Uint8Array,
        Uint16Array: Uint16Array,
        Uint32Array: Uint32Array,
        Float32Array: Float32Array,
        Float64Array: Float64Array
    };

    /**!
     * From [protobuf.js](https://github.com/protobufjs/protobuf.js/blob/master/lib/utf8/index.js)
     */
    var Utf8CoderJS = {
        measureLength: function (str) {
            var len = 0, c = 0;
            for (var i = 0; i < str.length; ++i) {
                c = str.charCodeAt(i);
                if (c < 128)
                    len += 1;
                else if (c < 2048)
                    len += 2;
                else if ((c & 0xFC00) === 0xD800 && (str.charCodeAt(i + 1) & 0xFC00) === 0xDC00) {
                    ++i;
                    len += 4;
                }
                else
                    len += 3;
            }
            return len;
        },
        write: function (str, buf, pos) {
            var start = pos, c1, // character 1
            c2; // character 2
            for (var i = 0; i < str.length; ++i) {
                c1 = str.charCodeAt(i);
                if (c1 < 128) {
                    buf[pos++] = c1;
                }
                else if (c1 < 2048) {
                    buf[pos++] = c1 >> 6 | 192;
                    buf[pos++] = c1 & 63 | 128;
                }
                else if ((c1 & 0xFC00) === 0xD800 && ((c2 = str.charCodeAt(i + 1)) & 0xFC00) === 0xDC00) {
                    c1 = 0x10000 + ((c1 & 0x03FF) << 10) + (c2 & 0x03FF);
                    ++i;
                    buf[pos++] = c1 >> 18 | 240;
                    buf[pos++] = c1 >> 12 & 63 | 128;
                    buf[pos++] = c1 >> 6 & 63 | 128;
                    buf[pos++] = c1 & 63 | 128;
                }
                else {
                    buf[pos++] = c1 >> 12 | 224;
                    buf[pos++] = c1 >> 6 & 63 | 128;
                    buf[pos++] = c1 & 63 | 128;
                }
            }
            return pos - start;
        },
        read: function (buf, pos, length) {
            if (length < 1) {
                return "";
            }
            var str = "";
            for (var i = pos, end = pos + length; i < end;) {
                var t = buf[i++];
                if (t <= 0x7F) {
                    str += String.fromCharCode(t);
                }
                else if (t >= 0xC0 && t < 0xE0) {
                    str += String.fromCharCode((t & 0x1F) << 6 | buf[i++] & 0x3F);
                }
                else if (t >= 0xE0 && t < 0xF0) {
                    str += String.fromCharCode((t & 0xF) << 12 | (buf[i++] & 0x3F) << 6 | buf[i++] & 0x3F);
                }
                else if (t >= 0xF0) {
                    var t2 = ((t & 7) << 18 | (buf[i++] & 0x3F) << 12 | (buf[i++] & 0x3F) << 6 | buf[i++] & 0x3F) - 0x10000;
                    str += String.fromCharCode(0xD800 + (t2 >> 10));
                    str += String.fromCharCode(0xDC00 + (t2 & 0x3FF));
                }
            }
            return str;
        }
    };
    var Utf8CoderNode = {
        measureLength: function (str) { return Buffer.byteLength(str, 'utf-8'); },
        write: function (str, buf, pos) { return Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength).write(str, pos, 'utf-8'); },
        read: function (buf, pos, length) { return Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength).toString('utf-8', pos, pos + length); }
    };
    /**
     * 自动判断环境，选择使用NodeJS Native方法编码或是JS编码
     */
    var Utf8Coder = typeof Buffer !== 'undefined' && Buffer.from && Buffer.prototype.write ? Utf8CoderNode : Utf8CoderJS;

    /** @internal */
    var Varint64 = /** @class */ (function () {
        function Varint64(high, low, byteLength) {
            this.uint32s = new Uint32Array([high, low]);
            if (byteLength !== undefined) {
                this._byteLength = byteLength;
            }
        }
        Varint64.from = function (value) {
            if (value === 0) {
                return this.Zero;
            }
            var sign = value < 0;
            if (sign) {
                value = -value;
            }
            var lo = value >>> 0, hi = (value - lo) / 4294967296 >>> 0;
            if (sign) {
                hi = ~hi >>> 0;
                lo = ~lo >>> 0;
                if (++lo > 4294967295) {
                    lo = 0;
                    if (++hi > 4294967295)
                        hi = 0;
                }
            }
            return new Varint64(hi, lo);
        };
        Varint64.prototype.toNumber = function (unsigned) {
            if (!unsigned && this.uint32s[0] >>> 31) {
                var low = ~this.uint32s[1] + 1 >>> 0, high = ~this.uint32s[0] >>> 0;
                if (!low)
                    high = high + 1 >>> 0;
                return -(low + high * 4294967296);
            }
            return this.uint32s[1] + this.uint32s[0] * 4294967296;
        };
        Varint64.prototype.zzEncode = function () {
            var mask = this.uint32s[0] >> 31;
            this.uint32s[0] = ((this.uint32s[0] << 1 | this.uint32s[1] >>> 31) ^ mask) >>> 0;
            this.uint32s[1] = (this.uint32s[1] << 1 ^ mask) >>> 0;
            return this;
        };
        Varint64.prototype.zzDecode = function () {
            var mask = -(this.uint32s[1] & 1);
            this.uint32s[1] = ((this.uint32s[1] >>> 1 | this.uint32s[0] << 31) ^ mask) >>> 0;
            this.uint32s[0] = (this.uint32s[0] >>> 1 ^ mask) >>> 0;
            return this;
        };
        Object.defineProperty(Varint64.prototype, "byteLength", {
            get: function () {
                if (this._byteLength === undefined) {
                    var part0 = this.uint32s[1], part1 = (this.uint32s[1] >>> 28 | this.uint32s[0] << 4) >>> 0, part2 = this.uint32s[0] >>> 24;
                    this._byteLength = part2 === 0
                        ? part1 === 0
                            ? part0 < 16384
                                ? part0 < 128 ? 1 : 2
                                : part0 < 2097152 ? 3 : 4
                            : part1 < 16384
                                ? part1 < 128 ? 5 : 6
                                : part1 < 2097152 ? 7 : 8
                        : part2 < 128 ? 9 : 10;
                }
                return this._byteLength;
            },
            enumerable: false,
            configurable: true
        });
        /**
         * 编码
         * @param buf
         * @param pos
         * @returns 编码后最新的pos
         */
        Varint64.prototype.writeToBuffer = function (buf, pos) {
            while (this.uint32s[0]) {
                buf[pos++] = this.uint32s[1] & 127 | 128;
                this.uint32s[1] = (this.uint32s[1] >>> 7 | this.uint32s[0] << 25) >>> 0;
                this.uint32s[0] >>>= 7;
            }
            while (this.uint32s[1] > 127) {
                buf[pos++] = this.uint32s[1] & 127 | 128;
                this.uint32s[1] = this.uint32s[1] >>> 7;
            }
            buf[pos++] = this.uint32s[1];
            return pos;
        };
        Varint64.readFromBuffer = function (buf, pos) {
            var startPos = pos;
            var hi = 0, lo = 0;
            var i = 0;
            if (buf.byteLength - pos > 4) { // fast route (lo)
                for (; i < 4; ++i) {
                    // 1st..4th
                    lo = (lo | (buf[pos] & 127) << i * 7) >>> 0;
                    if (buf[pos++] < 128)
                        return new Varint64(hi, lo, pos - startPos);
                }
                // 5th
                lo = (lo | (buf[pos] & 127) << 28) >>> 0;
                hi = (hi | (buf[pos] & 127) >> 4) >>> 0;
                if (buf[pos++] < 128)
                    return new Varint64(hi, lo, pos - startPos);
                i = 0;
            }
            else {
                for (; i < 3; ++i) {
                    /* istanbul ignore if */
                    if (pos >= buf.byteLength)
                        throw new Error('Read varint error: index out of range');
                    // 1st..3th
                    lo = (lo | (buf[pos] & 127) << i * 7) >>> 0;
                    if (buf[pos++] < 128)
                        return new Varint64(hi, lo, pos - startPos);
                }
                // 4th
                lo = (lo | (buf[pos++] & 127) << i * 7) >>> 0;
                return new Varint64(hi, lo, pos - startPos);
            }
            if (buf.byteLength - pos > 4) { // fast route (hi)
                for (; i < 5; ++i) {
                    // 6th..10th
                    hi = (hi | (buf[pos] & 127) << i * 7 + 3) >>> 0;
                    if (buf[pos++] < 128)
                        return new Varint64(hi, lo, pos - startPos);
                }
            }
            else {
                for (; i < 5; ++i) {
                    /* istanbul ignore if */
                    if (pos >= buf.byteLength)
                        throw new Error('Read varint error: index out of range');
                    // 6th..10th
                    hi = (hi | (buf[pos] & 127) << i * 7 + 3) >>> 0;
                    if (buf[pos++] < 128)
                        return new Varint64(hi, lo, pos - startPos);
                }
            }
            /* istanbul ignore next */
            throw Error("invalid varint encoding");
        };
        Varint64.Zero = new Varint64(0, 0);
        return Varint64;
    }());

    var BufferReader = /** @class */ (function () {
        function BufferReader() {
            this._pos = 0;
        }
        BufferReader.prototype.load = function (buf, pos) {
            if (pos === void 0) { pos = 0; }
            this._buf = buf;
            this._pos = pos;
            this._view = new DataView(buf.buffer);
        };
        BufferReader.prototype.readVarint = function () {
            var varint = Varint64.readFromBuffer(this._buf, this._pos);
            this._pos += varint.byteLength;
            return varint;
        };
        BufferReader.prototype.readUint = function () {
            return this.readVarint().toNumber(true);
        };
        BufferReader.prototype.readInt = function () {
            return this.readVarint().zzDecode().toNumber();
        };
        BufferReader.prototype.readDouble = function () {
            var pos = this._pos;
            this._pos += 8;
            return this._view.getFloat64(this._buf.byteOffset + pos);
        };
        BufferReader.prototype.readString = function () {
            var strByteLength = this.readUint();
            var str = Utf8Coder.read(this._buf, this._pos, strByteLength);
            this._pos += strByteLength;
            return str;
        };
        BufferReader.prototype.readBuffer = function () {
            var bufByteLength = this.readUint();
            var buf = this._buf.subarray(this._pos, this._pos + bufByteLength);
            this._pos += bufByteLength;
            return buf;
        };
        BufferReader.prototype.skip = function (byteLength) {
            this._pos += byteLength;
        };
        BufferReader.prototype.skipByLengthType = function (lengthType) {
            if (lengthType === LengthType.Bit64) {
                this._pos += 8;
            }
            else if (lengthType === LengthType.Varint) {
                this.readVarint();
            }
            else if (lengthType === LengthType.LengthDelimited) {
                var bufByteLength = this.readUint();
                this._pos += bufByteLength;
            }
            else if (lengthType === LengthType.IdBlock) {
                this.skipIdBlock();
            }
            else {
                throw new Error('Unknown lengthType: ' + lengthType);
            }
        };
        BufferReader.prototype.skipIdBlock = function () {
            var idNum = this.readUint();
            for (var i = 0; i < idNum; ++i) {
                var id = this.readUint();
                var lengthType = id & 3;
                this.skipByLengthType(lengthType);
            }
        };
        BufferReader.prototype.readBoolean = function () {
            var value = this._view.getUint8(this._buf.byteOffset + this._pos++);
            if (value === 255) {
                return true;
            }
            else if (value === 0) {
                return false;
            }
            else {
                throw new Error("Invalid boolean encoding [".concat(value, "] at pos ").concat(this._pos - 1));
            }
        };
        Object.defineProperty(BufferReader.prototype, "unreadByteLength", {
            get: function () {
                return this._buf.byteLength - this._pos;
            },
            enumerable: false,
            configurable: true
        });
        BufferReader.prototype.dispose = function () {
            this._buf = this._view = undefined;
        };
        return BufferReader;
    }());

    /** @internal */
    var Decoder = /** @class */ (function () {
        function Decoder(options) {
            this._options = options;
            this._reader = new BufferReader();
            this._validator = options.validator;
        }
        Decoder.prototype.decode = function (buffer, schema) {
            this._reader.load(buffer);
            return this._read(schema);
        };
        Decoder.prototype.decodeJSON = function (json, schema) {
            var _this = this;
            if (json === null || CoderUtil.isJsonCompatible(schema, 'decode', this._validator.protoHelper)) {
                return json;
            }
            // 递归 只处理 ArrayBuffer、Date、ObjectId
            switch (schema.type) {
                case SchemaType.Array:
                    if (!Array.isArray(json)) {
                        break;
                    }
                    return json.map(function (v) { return _this.decodeJSON(v, schema.elementType); });
                case SchemaType.Tuple:
                    if (!Array.isArray(json)) {
                        break;
                    }
                    return json.map(function (v, i) { return _this.decodeJSON(v, schema.elementTypes[i]); });
                case SchemaType.Interface:
                    if (json.constructor !== Object) {
                        break;
                    }
                    json = Object.assign({}, json);
                    var flatSchema = this._validator.protoHelper.getFlatInterfaceSchema(schema);
                    var _loop_1 = function (key) {
                        var property = flatSchema.properties.find(function (v) { return v.name === key; });
                        if (property) {
                            json[key] = this_1.decodeJSON(json[key], property.type);
                        }
                        else if (flatSchema.indexSignature) {
                            json[key] = this_1.decodeJSON(json[key], flatSchema.indexSignature.type);
                        }
                    };
                    var this_1 = this;
                    for (var key in json) {
                        _loop_1(key);
                    }
                    return json;
                case SchemaType.Date:
                    if (typeof json !== 'string' && typeof json !== 'number') {
                        break;
                    }
                    return new Date(json);
                case SchemaType.Partial:
                case SchemaType.Pick:
                case SchemaType.Omit:
                case SchemaType.Overwrite:
                    var parsed = this._validator.protoHelper.parseMappedType(schema);
                    if (parsed.type === SchemaType.Interface) {
                        if (json.constructor !== Object) {
                            break;
                        }
                        json = Object.assign({}, json);
                        var flatSchema_1 = this._validator.protoHelper.getFlatInterfaceSchema(schema);
                        var _loop_2 = function (key) {
                            var property = flatSchema_1.properties.find(function (v) { return v.name === key; });
                            if (property) {
                                json[key] = this_2.decodeJSON(json[key], property.type);
                            }
                            else if (flatSchema_1.indexSignature) {
                                json[key] = this_2.decodeJSON(json[key], flatSchema_1.indexSignature.type);
                            }
                        };
                        var this_2 = this;
                        for (var key in json) {
                            _loop_2(key);
                        }
                        return json;
                    }
                    else if (parsed.type === SchemaType.Union || parsed.type === SchemaType.Intersection) {
                        for (var _i = 0, _a = parsed.members; _i < _a.length; _i++) {
                            var member = _a[_i];
                            json = this.decodeJSON(json, member.type);
                        }
                        return json;
                    }
                    break;
                case SchemaType.Buffer:
                    if (typeof json !== 'string') {
                        break;
                    }
                    var uint8Arr = Base64Util.base64ToBuffer(json);
                    return this._getBufferValue(uint8Arr, schema);
                case SchemaType.IndexedAccess:
                case SchemaType.Reference:
                case SchemaType.Keyof:
                    return this.decodeJSON(json, this._validator.protoHelper.parseReference(schema));
                case SchemaType.Union:
                case SchemaType.Intersection: {
                    // 逐个编码 然后合并 （失败的会原值返回，所以不影响结果）
                    for (var _b = 0, _c = schema.members; _b < _c.length; _b++) {
                        var member = _c[_b];
                        json = this.decodeJSON(json, member.type);
                    }
                    return json;
                }
                case SchemaType.NonNullable:
                    return this.decodeJSON(json, schema.target);
                case SchemaType.Custom:
                    if (schema.decodeJSON) {
                        return schema.decodeJSON(json);
                    }
                    break;
                default:
                    schema.type;
            }
            return json;
        };
        Decoder.prototype._read = function (schema) {
            switch (schema.type) {
                case SchemaType.Boolean:
                    return this._reader.readBoolean();
                case SchemaType.Number:
                    return this._readNumber(schema);
                case SchemaType.String:
                    return this._reader.readString();
                case SchemaType.Array: {
                    var output = [];
                    // 数组长度：Varint
                    var length_1 = this._reader.readUint();
                    for (var i = 0; i < length_1; ++i) {
                        var item = this._read(schema.elementType);
                        output.push(item);
                    }
                    return output;
                }
                case SchemaType.Tuple: {
                    if (schema.elementTypes.length > 64) {
                        throw new Error('Elements oversized, maximum supported tuple elements is 64, now get ' + schema.elementTypes.length);
                    }
                    var output = [];
                    // PayloadMask: Varint64
                    var payloadMask = this._reader.readVarint();
                    // 计算maskIndices
                    var maskIndices = [];
                    // Low
                    for (var i = 0; i < 32; ++i) {
                        if (payloadMask.uint32s[1] & 1 << i) {
                            maskIndices.push(i);
                        }
                    }
                    // High
                    for (var i = 0; i < 32; ++i) {
                        if (payloadMask.uint32s[0] & 1 << i) {
                            maskIndices.push(i + 32);
                        }
                    }
                    if (!maskIndices.length) {
                        return [];
                    }
                    var maxIndex = maskIndices.last();
                    for (var i = 0, nextMaskIndex = 0, next = maskIndices[0]; i <= maxIndex; ++i) {
                        if (i === next) {
                            output[i] = this._read(schema.elementTypes[i]);
                            ++nextMaskIndex;
                            next = maskIndices[nextMaskIndex];
                        }
                        else {
                            output[i] = undefined;
                        }
                    }
                    // undefined as null
                    for (var i = 0; i < schema.elementTypes.length; ++i) {
                        if (this._undefinedAsNull(output[i], schema.elementTypes[i], schema.optionalStartIndex !== undefined && i >= schema.optionalStartIndex)) {
                            output[i] = null;
                        }
                    }
                    return output;
                }
                case SchemaType.Enum:
                    var enumId_1 = this._reader.readVarint().toNumber();
                    var enumItem = schema.members.find(function (v) { return v.id === enumId_1; });
                    if (!enumItem) {
                        throw new Error("Invalid enum encoding: unexpected id ".concat(enumId_1));
                    }
                    return enumItem.value;
                case SchemaType.Any:
                case SchemaType.Object:
                    var jsonStr = this._reader.readString();
                    if (jsonStr === 'undefined') {
                        return undefined;
                    }
                    return JSON.parse(jsonStr);
                case SchemaType.Literal:
                    return schema.literal;
                case SchemaType.Interface:
                    return this._readInterface(schema);
                case SchemaType.Buffer:
                    var uint8Arr = this._reader.readBuffer();
                    return this._getBufferValue(uint8Arr, schema);
                case SchemaType.IndexedAccess:
                case SchemaType.Reference:
                case SchemaType.Keyof:
                    return this._read(this._validator.protoHelper.parseReference(schema));
                case SchemaType.Partial:
                case SchemaType.Pick:
                case SchemaType.Omit:
                case SchemaType.Overwrite:
                    var parsed = this._validator.protoHelper.parseMappedType(schema);
                    if (parsed.type === SchemaType.Interface) {
                        return this._readPureMappedType(schema);
                    }
                    else {
                        return this._readUnionOrIntersection(parsed);
                    }
                case SchemaType.Union:
                case SchemaType.Intersection:
                    return this._readUnionOrIntersection(schema);
                case SchemaType.Date:
                    return new Date(this._reader.readUint());
                case SchemaType.NonNullable:
                    return this._read(schema.target);
                case SchemaType.Custom:
                    if (!schema.decode) {
                        throw new Error('Missing decode method for CustomTypeSchema');
                    }
                    var buf = this._reader.readBuffer();
                    return schema.decode(buf);
                default:
                    // @ts-expect-error
                    throw new Error("Unrecognized schema type: ".concat(schema.type));
            }
        };
        /**
         * PureMappedType 每一层的target 都是MappedType或Interface（最终层）
         */
        Decoder.prototype._readPureMappedType = function (schema) {
            var output;
            var overwrite;
            if (schema.type === 'Overwrite') {
                // Overwrite Block
                overwrite = this._read(schema.overwrite);
            }
            var parsedTarget = this._validator.protoHelper.parseReference(schema.target);
            if (parsedTarget.type === 'Interface') {
                output = this._readInterface(parsedTarget);
            }
            else if (parsedTarget.type === 'Pick' || parsedTarget.type === 'Omit' || parsedTarget.type === 'Partial' || parsedTarget.type === 'Overwrite') {
                output = this._readPureMappedType(parsedTarget);
            }
            else {
                throw new Error('Invalid PureMappedType child: ' + schema.type);
            }
            // filter key
            if (schema.type === 'Pick') {
                // 把Pick以外的剔除
                for (var key in output) {
                    if (schema.keys.indexOf(key) === -1) {
                        delete output[key];
                    }
                }
            }
            else if (schema.type === 'Omit') {
                // 剔除Omit
                for (var key in output) {
                    if (schema.keys.indexOf(key) > -1) {
                        delete output[key];
                    }
                }
            }
            else if (schema.type === 'Overwrite') {
                Object.assign(output, overwrite);
            }
            // Partial 原样返回
            return output;
        };
        Decoder.prototype._readNumber = function (schema) {
            // 默认为double
            var scalarType = schema.scalarType || 'double';
            switch (scalarType) {
                // 定长编码
                case 'double':
                    return this._reader.readDouble();
                // Varint编码
                case 'int':
                    return this._reader.readInt();
                case 'uint':
                    return this._reader.readUint();
                default:
                    throw new Error('Scalar type not support : ' + scalarType);
            }
        };
        Decoder.prototype._readInterface = function (schema) {
            var output = {};
            var flatSchema = this._validator.protoHelper.getFlatInterfaceSchema(schema);
            // BlockID数量
            var blockIdNum = this._reader.readUint();
            var _loop_3 = function (i) {
                // ReadBlock
                var readBlockId = this_3._reader.readUint();
                var lengthType = readBlockId & 3;
                var blockId = readBlockId >> 2;
                // indexSignature
                if (blockId === 0) {
                    if (flatSchema.indexSignature) {
                        var type = flatSchema.indexSignature.type;
                        var fieldName = this_3._reader.readString();
                        this_3._skipIdLengthPrefix(this_3._validator.protoHelper.parseReference(type));
                        output[fieldName] = this_3._read(type);
                    }
                    // indexSignature未定义，可能是新协议，此处兼容，根据lengthType跳过
                    else {
                        // skip fieldName
                        this_3._reader.skipByLengthType(LengthType.LengthDelimited);
                        // skipPayload
                        this_3._reader.skipByLengthType(lengthType);
                    }
                }
                // extend block
                else if (blockId <= 9) {
                    var extendId_1 = blockId - 1;
                    var extend = schema.extends && schema.extends.find(function (v) { return v.id === extendId_1; });
                    if (extend) {
                        this_3._skipIdLengthPrefix(this_3._validator.protoHelper.parseReference(extend.type));
                        var extendValue = this_3._read(extend.type);
                        Object.assign(output, extendValue);
                    }
                    // 未知的extendId 可能是新协议 跳过
                    else {
                        // skipPayload
                        this_3._reader.skipByLengthType(lengthType);
                    }
                }
                // property
                else {
                    var propertyId_1 = blockId - 10;
                    var property = schema.properties && schema.properties.find(function (v) { return v.id === propertyId_1; });
                    if (property) {
                        this_3._skipIdLengthPrefix(this_3._validator.protoHelper.parseReference(property.type));
                        output[property.name] = this_3._read(property.type);
                    }
                    // 未知的PropertyID 可能是新协议 跳过
                    else {
                        // skipPayload
                        this_3._reader.skipByLengthType(lengthType);
                    }
                }
            };
            var this_3 = this;
            for (var i = 0; i < blockIdNum; ++i) {
                _loop_3();
            }
            // Literal property 由于不编码 将其补回
            // undefined as null
            for (var _i = 0, _a = flatSchema.properties; _i < _a.length; _i++) {
                var property = _a[_i];
                if (output.hasOwnProperty(property.name)) {
                    continue;
                }
                // Literal
                var parsedType = this._validator.protoHelper.parseReference(property.type);
                if (parsedType.type === 'Literal') {
                    output[property.name] = parsedType.literal;
                    continue;
                }
                // undefined as null
                if (this._undefinedAsNull(output[property.name], parsedType, property.optional)) {
                    output[property.name] = null;
                    continue;
                }
            }
            return output;
        };
        /** @internal 是否该null值小于当做undefined编码 */
        Decoder.prototype._undefinedAsNull = function (value, type, isOptional) {
            return value === undefined
                && this._options.undefinedAsNull
                && !SchemaUtil.canBeLiteral(type, undefined) && !isOptional
                && SchemaUtil.canBeLiteral(type, null);
        };
        Decoder.prototype._skipIdLengthPrefix = function (parsedSchema) {
            var lengthInfo = IdBlockUtil.getPayloadLengthInfo(parsedSchema, this._validator.protoHelper);
            if (lengthInfo.needLengthPrefix) {
                // skip length prefix
                this._reader.skipByLengthType(LengthType.Varint);
            }
        };
        Decoder.prototype._readUnionOrIntersection = function (schema) {
            var output;
            var idNum = this._reader.readUint();
            var _loop_4 = function (i) {
                var readId = this_4._reader.readUint();
                var lengthType = readId & 3;
                var id = readId >> 2;
                var member = schema.members.find(function (v) { return v.id === id; });
                // 不可识别的Member，可能是新协议，跳过使兼容
                if (!member) {
                    this_4._reader.skipByLengthType(lengthType);
                    return "continue";
                }
                this_4._skipIdLengthPrefix(this_4._validator.protoHelper.parseReference(member.type));
                var value = this_4._read(member.type);
                if (this_4._isObject(output) && this_4._isObject(value)) {
                    Object.assign(output, value);
                }
                else {
                    output = value;
                }
            };
            var this_4 = this;
            for (var i = 0; i < idNum; ++i) {
                _loop_4();
            }
            if (this._undefinedAsNull(output, schema)) {
                output = null;
            }
            return output;
        };
        Decoder.prototype._isObject = function (value) {
            return typeof (value) === 'object' && value !== null;
        };
        Decoder.prototype._getBufferValue = function (uint8Arr, schema) {
            if (schema.arrayType) {
                if (schema.arrayType === 'BigInt64Array' || schema.arrayType === 'BigUint64Array') {
                    throw new Error('Unsupported arrayType: ' + schema.arrayType);
                }
                // Uint8Array 性能最高
                else if (schema.arrayType === 'Uint8Array') {
                    return uint8Arr;
                }
                // 其余TypedArray 可能需要内存拷贝 性能次之
                else {
                    var typedArr = TypedArrays[schema.arrayType];
                    // 字节对齐，可以直接转，无需拷贝内存
                    if (uint8Arr.byteOffset % typedArr.BYTES_PER_ELEMENT === 0) {
                        return new typedArr(uint8Arr.buffer, uint8Arr.byteOffset, uint8Arr.byteLength / typedArr.BYTES_PER_ELEMENT);
                    }
                    // 字节不对齐，不能直接转，只能拷贝内存后再生成
                    else {
                        var arrBuf = uint8Arr.buffer.slice(uint8Arr.byteOffset, uint8Arr.byteOffset + uint8Arr.byteLength);
                        return new typedArr(arrBuf);
                    }
                }
            }
            else {
                return uint8Arr.byteLength === uint8Arr.buffer.byteLength && uint8Arr.byteOffset === 0 ? uint8Arr.buffer
                    : uint8Arr.buffer.slice(uint8Arr.byteOffset, uint8Arr.byteOffset + uint8Arr.byteLength);
            }
        };
        return Decoder;
    }());

    /** @internal */
    var Config = {
        interface: {
            maxExtendsNum: 9
        }
    };

    /**
     * 用Op来串联 next
     * Op包含 function next length
     * 先度量长度再执行编码
     * 一次性编码
     * 使用BufferPool
     * writer.uint32(xx).string(xxx).finish();
     * @internal
     */
    var BufferWriter = /** @class */ (function () {
        function BufferWriter() {
            this._ops = [];
        }
        Object.defineProperty(BufferWriter.prototype, "ops", {
            get: function () {
                return this._ops;
            },
            enumerable: false,
            configurable: true
        });
        BufferWriter.prototype.clear = function () {
            this._ops = [];
        };
        BufferWriter.prototype.push = function (req) {
            this._ops.push(this.req2op(req));
            return this;
        };
        BufferWriter.prototype.req2op = function (req) {
            if (req.type === 'string' || req.type === 'buffer') {
                var valueLength = this.measureLength(req);
                // Length
                this.push({ type: 'varint', value: Varint64.from(valueLength) });
                // Value
                return __assign(__assign({}, req), { length: valueLength });
            }
            else {
                var length_1 = this.measureLength(req);
                return __assign(__assign({}, req), { length: length_1 });
            }
        };
        BufferWriter.prototype.measureLength = function (req) {
            switch (req.type) {
                case 'varint':
                    return req.value.byteLength;
                case 'string':
                    return Utf8Coder.measureLength(req.value);
                case 'buffer':
                    return req.value.byteLength;
                case 'double':
                    return 8;
                case 'boolean':
                    return 1;
                default:
                    return NaN;
            }
        };
        BufferWriter.prototype.finish = function () {
            var byteLength = this._ops.sum(function (v) { return v.length; });
            var pos = 0;
            var buf = new Uint8Array(byteLength);
            var view = new DataView(buf.buffer);
            for (var _i = 0, _a = this._ops; _i < _a.length; _i++) {
                var op = _a[_i];
                switch (op.type) {
                    case 'varint':
                        var newPos = op.value.writeToBuffer(buf, pos);
                        if (newPos !== pos + op.length) {
                            throw new Error("Error varint measuredLength ".concat(op.length, ", actual is ").concat(newPos - pos, ", value is ").concat(op.value.toNumber()));
                        }
                        break;
                    case 'double':
                        view.setFloat64(buf.byteOffset + pos, op.value);
                        break;
                    case 'string':
                        var encLen = Utf8Coder.write(op.value, buf, pos);
                        if (encLen !== op.length) {
                            throw new Error("Expect ".concat(op.length, " bytes but encoded ").concat(encLen, " bytes"));
                        }
                        break;
                    case 'buffer':
                        buf.subarray(pos, pos + op.length).set(op.value);
                        break;
                    case 'boolean':
                        view.setUint8(buf.byteOffset + pos, op.value ? 255 : 0);
                        break;
                }
                pos += op.length;
            }
            return buf;
        };
        return BufferWriter;
    }());

    /** @internal */
    var Encoder = /** @class */ (function () {
        function Encoder(options) {
            this._options = options;
            this._writer = new BufferWriter();
            this._validator = options.validator;
        }
        Encoder.prototype.encode = function (value, schema) {
            this._writer.clear();
            this._write(value, schema);
            return this._writer.finish();
        };
        Encoder.prototype.encodeJSON = function (value, schema) {
            var _this = this;
            // JSON 能直接传输的类型，直接跳过
            if (typeof value !== 'object' || value === null || CoderUtil.isJsonCompatible(schema, 'encode', this._validator.protoHelper)) {
                return value;
            }
            switch (schema.type) {
                case SchemaType.Array:
                    if (!Array.isArray(value)) {
                        break;
                    }
                    return value.map(function (v) { return _this.encodeJSON(v, schema.elementType); });
                case SchemaType.Tuple: {
                    if (!Array.isArray(value)) {
                        break;
                    }
                    return value.map(function (v, i) { return _this.encodeJSON(v, schema.elementTypes[i]); });
                }
                case SchemaType.Interface: {
                    if (value.constructor !== Object) {
                        break;
                    }
                    value = Object.assign({}, value);
                    var flatSchema = this._validator.protoHelper.getFlatInterfaceSchema(schema);
                    var _loop_1 = function (key) {
                        var property = flatSchema.properties.find(function (v) { return v.name === key; });
                        if (property) {
                            value[key] = this_1.encodeJSON(value[key], property.type);
                        }
                        else if (flatSchema.indexSignature) {
                            value[key] = this_1.encodeJSON(value[key], flatSchema.indexSignature.type);
                        }
                    };
                    var this_1 = this;
                    for (var key in value) {
                        _loop_1(key);
                    }
                    return value;
                }
                case SchemaType.Partial:
                case SchemaType.Pick:
                case SchemaType.Omit:
                case SchemaType.Overwrite:
                    var parsed = this._validator.protoHelper.parseMappedType(schema);
                    return this.encodeJSON(value, parsed);
                case SchemaType.Buffer:
                    if (!(value instanceof ArrayBuffer) && !ArrayBuffer.isView(value)) {
                        break;
                    }
                    if (schema.arrayType) {
                        if (schema.arrayType === 'Uint8Array') {
                            return Base64Util.bufferToBase64(value);
                        }
                        var view = value;
                        var buf = view.byteLength === view.buffer.byteLength && view.byteOffset === 0 ? view.buffer
                            : view.buffer.slice(view.byteOffset, view.byteOffset + view.byteLength);
                        return Base64Util.bufferToBase64(new Uint8Array(buf));
                    }
                    else {
                        return Base64Util.bufferToBase64(new Uint8Array(value));
                    }
                case SchemaType.IndexedAccess:
                case SchemaType.Reference:
                case SchemaType.Keyof:
                    return this.encodeJSON(value, this._validator.protoHelper.parseReference(schema));
                case SchemaType.Union:
                case SchemaType.Intersection: {
                    // 逐个编码 然后合并 （失败的会原值返回，所以不影响结果）
                    for (var _i = 0, _a = schema.members; _i < _a.length; _i++) {
                        var member = _a[_i];
                        value = this.encodeJSON(value, member.type);
                    }
                    return value;
                }
                case SchemaType.NonNullable:
                    return this.encodeJSON(value, schema.target);
                case SchemaType.Date:
                    if (!(value instanceof Date)) {
                        break;
                    }
                    return value.toJSON();
                case SchemaType.Custom:
                    if (schema.encodeJSON) {
                        return schema.encodeJSON(value);
                    }
                    else if (typeof (value === null || value === void 0 ? void 0 : value.toJSON) === 'function') {
                        return value.toJSON();
                    }
                    else if (typeof (value === null || value === void 0 ? void 0 : value.toString) === 'function') {
                        return value.toString();
                    }
                    return value;
                default:
                    schema.type;
            }
            return value;
        };
        Encoder.prototype._write = function (value, schema, options) {
            switch (schema.type) {
                case SchemaType.Boolean:
                    this._writer.push({ type: 'boolean', value: value });
                    break;
                case SchemaType.Number:
                    this._writeNumber(value, schema);
                    break;
                case SchemaType.String:
                    this._writer.push({ type: 'string', value: value });
                    break;
                case SchemaType.Array: {
                    var _v = value;
                    // 数组长度：Varint
                    this._writer.push({ type: 'varint', value: Varint64.from(_v.length) });
                    // Element Payload
                    for (var i = 0; i < _v.length; ++i) {
                        this._write(_v[i], schema.elementType);
                    }
                    break;
                }
                case SchemaType.Tuple: {
                    if (schema.elementTypes.length > 64) {
                        throw new Error('Elements oversized, maximum supported tuple elements is 64, now get ' + schema.elementTypes.length);
                    }
                    var _v = value;
                    // 计算maskPos（要编码的值的index）
                    var maskIndices = [];
                    for (var i = 0; i < _v.length; ++i) {
                        // undefined 不编码
                        // null as undefined
                        if (_v[i] === undefined || this._nullAsUndefined(_v[i], schema.elementTypes[i])) {
                            continue;
                        }
                        maskIndices.push(i);
                    }
                    // 生成PayloadMask：Varint64
                    var lo = 0;
                    var hi = 0;
                    for (var _i = 0, maskIndices_1 = maskIndices; _i < maskIndices_1.length; _i++) {
                        var v = maskIndices_1[_i];
                        if (v < 32) {
                            lo |= 1 << v;
                        }
                        else {
                            hi |= 1 << v - 32;
                        }
                    }
                    this._writer.push({ type: 'varint', value: new Varint64(hi, lo) });
                    // Element Payload
                    for (var _a = 0, maskIndices_2 = maskIndices; _a < maskIndices_2.length; _a++) {
                        var i = maskIndices_2[_a];
                        this._write(_v[i], schema.elementTypes[i]);
                    }
                    break;
                }
                case SchemaType.Enum:
                    var enumItem = schema.members.find(function (v) { return v.value === value; });
                    if (!enumItem) {
                        throw new Error("Unexpect enum value: ".concat(value));
                    }
                    this._writer.push({ type: 'varint', value: Varint64.from(enumItem.id) });
                    break;
                case SchemaType.Any:
                    if (value === undefined) {
                        this._writer.push({ type: 'string', value: 'undefined' });
                    }
                    else {
                        this._writer.push({ type: 'string', value: JSON.stringify(value) });
                    }
                    break;
                case SchemaType.Object:
                    this._writer.push({ type: 'string', value: JSON.stringify(value) });
                    break;
                case SchemaType.Literal:
                    break;
                case SchemaType.Interface:
                    this._writeInterface(value, schema, options);
                    break;
                case SchemaType.Buffer:
                    this._writeBuffer(value);
                    break;
                case SchemaType.IndexedAccess:
                case SchemaType.Reference:
                case SchemaType.Keyof:
                    this._write(value, this._validator.protoHelper.parseReference(schema), options);
                    break;
                case SchemaType.Partial:
                case SchemaType.Pick:
                case SchemaType.Omit:
                case SchemaType.Overwrite:
                    var parsed = this._validator.protoHelper.parseMappedType(schema);
                    if (parsed.type === SchemaType.Interface) {
                        this._writePureMappedType(value, schema, options);
                    }
                    else if (parsed.type === SchemaType.Union) {
                        this._writeUnion(value, parsed, options === null || options === void 0 ? void 0 : options.skipFields);
                    }
                    else if (parsed.type === SchemaType.Intersection) {
                        this._writeIntersection(value, parsed, options === null || options === void 0 ? void 0 : options.skipFields);
                    }
                    break;
                case SchemaType.Union:
                    this._writeUnion(value, schema, options === null || options === void 0 ? void 0 : options.skipFields);
                    break;
                case SchemaType.Intersection:
                    this._writeIntersection(value, schema, options === null || options === void 0 ? void 0 : options.skipFields);
                    break;
                case SchemaType.Date:
                    this._writer.push({ type: 'varint', value: Varint64.from(value.getTime()) });
                    break;
                case SchemaType.NonNullable:
                    this._write(value, schema.target, options);
                    break;
                case SchemaType.Custom:
                    if (!schema.encode) {
                        throw new Error('Missing encode method for CustomTypeSchema');
                    }
                    var buf = schema.encode(value);
                    // 以 Buffer 形式写入
                    this._writeBuffer(buf);
                    break;
                default:
                    // @ts-expect-error
                    throw new Error("Unrecognized schema type: ".concat(schema.type));
            }
        };
        Encoder.prototype._writePureMappedType = function (value, schema, options) {
            if (!options) {
                options = {};
            }
            if (schema.type === 'Pick') {
                // 已存在 取交集
                if (options.pickFields) {
                    var newPickFields = {};
                    for (var _i = 0, _a = schema.keys; _i < _a.length; _i++) {
                        var v = _a[_i];
                        if (options.pickFields[v]) {
                            newPickFields[v] = 1;
                        }
                    }
                    options.pickFields = newPickFields;
                }
                // 不存在 初始化
                else {
                    options.pickFields = {};
                    for (var _b = 0, _c = schema.keys; _b < _c.length; _b++) {
                        var v = _c[_b];
                        options.pickFields[v] = 1;
                    }
                }
            }
            else if (schema.type === 'Omit') {
                // 不存在 初始化
                if (!(options === null || options === void 0 ? void 0 : options.skipFields)) {
                    if (!options) {
                        options = {};
                    }
                    options.skipFields = {};
                }
                // 取并集                
                for (var _d = 0, _e = schema.keys; _d < _e.length; _d++) {
                    var v = _e[_d];
                    options.skipFields[v] = 1;
                }
            }
            else if (schema.type === 'Overwrite') {
                var parsed = this._parseOverwrite(value, schema);
                // 写入Overwrite部分
                this._write(parsed.overwriteValue, parsed.overwrite, options);
            }
            else if (schema.type === 'Partial') ;
            else {
                // @ts-expect-error
                throw new Error('Invalid PureMappedType child: ' + schema.type);
            }
            // Write Interface
            var parsedTarget = this._validator.protoHelper.parseReference(schema.target);
            if (parsedTarget.type === 'Interface') {
                this._writeInterface(value, parsedTarget, options);
            }
            else {
                this._writePureMappedType(value, parsedTarget, options);
            }
        };
        Encoder.prototype._writeNumber = function (value, schema) {
            // 默认为double
            var scalarType = schema.scalarType || 'double';
            switch (scalarType) {
                // 定长编码
                case 'double':
                    this._writer.push({ type: scalarType, value: value });
                    break;
                // Varint编码
                case 'int':
                    this._writer.push({ type: 'varint', value: Varint64.from(value).zzEncode() });
                    break;
                case 'uint':
                    this._writer.push({ type: 'varint', value: Varint64.from(value) });
                    break;
                default:
                    throw new Error('Scalar type not support : ' + scalarType);
            }
        };
        Encoder.prototype._writeInterface = function (value, schema, options) {
            // skipFields默认值
            if (!options) {
                options = {};
            }
            if (!options.skipFields) {
                options.skipFields = {};
            }
            // 记录起始op位置，用于最后插入BlockID数量
            var opStartOps = this._writer.ops.length;
            var blockIdCount = 0;
            // 以下，interface
            // extends
            if (schema.extends) {
                // 支持的继承数量有上限
                if (schema.extends.length > Config.interface.maxExtendsNum) {
                    throw new Error("Max support ".concat(Config.interface.maxExtendsNum, " extends, actual: ").concat(schema.extends.length));
                }
                for (var _i = 0, _a = schema.extends; _i < _a.length; _i++) {
                    var extend = _a[_i];
                    // BlockID = extend.id + 1
                    var blockId = extend.id + 1;
                    this._writer.push({ type: 'varint', value: Varint64.from(blockId) });
                    var blockIdPos = this._writer.ops.length - 1;
                    // 写入extend interface前 writeOps的长度
                    var opsLengthBeforeWrite = this._writer.ops.length;
                    // extend Block
                    var parsedExtend = this._validator.protoHelper.parseReference(extend.type);
                    this._writeInterface(value, parsedExtend, __assign(__assign({}, options), { 
                        // 确保indexSignature是在最小层级编码
                        skipIndexSignature: !!schema.indexSignature || options.skipIndexSignature // 如果父级有indexSignature 或 父级跳过 则跳过indexSignature
                     }));
                    // 写入前后writeOps只增加了一个（block length），说明该extend并未写入任何property字段，取消编码这个block
                    if (this._writer.ops.length === opsLengthBeforeWrite + 1) {
                        // 移除BlockID
                        this._writer.ops.splice(this._writer.ops.length - 2, 2);
                    }
                    // extend写入成功 blockId数量+1
                    else {
                        ++blockIdCount;
                        this._processIdWithLengthType(blockIdPos, extend.type);
                    }
                }
            }
            // property
            if (schema.properties) {
                for (var _b = 0, _c = schema.properties; _b < _c.length; _b++) {
                    var property = _c[_b];
                    var parsedType = this._validator.protoHelper.parseReference(property.type);
                    var propValue = value[property.name];
                    // PickFields
                    if (options.pickFields && !options.pickFields[property.name]) {
                        continue;
                    }
                    // Literal不编码 直接跳过
                    if (parsedType.type === 'Literal') {
                        options.skipFields[property.name] = 1;
                        continue;
                    }
                    // null as undefined
                    if (this._nullAsUndefined(propValue, property.type)) {
                        propValue = undefined;
                    }
                    // undefined不编码
                    if (propValue === undefined) {
                        continue;
                    }
                    // SkipFields
                    if (options.skipFields[property.name]) {
                        continue;
                    }
                    options.skipFields[property.name] = 1;
                    var blockId = property.id + Config.interface.maxExtendsNum + 1;
                    // BlockID (propertyID)
                    this._writer.push({ type: 'varint', value: Varint64.from(blockId) });
                    var blockIdPos = this._writer.ops.length - 1;
                    // Value Payload
                    this._write(propValue, parsedType);
                    ++blockIdCount;
                    this._processIdWithLengthType(blockIdPos, parsedType);
                }
            }
            // indexSignature
            if (!options.skipIndexSignature) {
                var flat = this._validator.protoHelper.getFlatInterfaceSchema(schema);
                if (flat.indexSignature) {
                    for (var key in value) {
                        if (value[key] === undefined || this._nullAsUndefined(value[key], flat.indexSignature.type)) {
                            continue;
                        }
                        // PickFields
                        if (options.pickFields && !options.pickFields[key]) {
                            continue;
                        }
                        // SkipFields
                        if (options.skipFields[key]) {
                            continue;
                        }
                        options.skipFields[key] = 1;
                        // BlockID == 0
                        this._writer.push({ type: 'varint', value: Varint64.from(0) });
                        var blockIdPos = this._writer.ops.length - 1;
                        // 字段名
                        this._writer.push({ type: 'string', value: key });
                        var lengthPrefixPos = this._writer.ops.length;
                        // Value Payload
                        this._write(value[key], flat.indexSignature.type);
                        ++blockIdCount;
                        this._processIdWithLengthType(blockIdPos, flat.indexSignature.type, lengthPrefixPos);
                    }
                }
            }
            this._writer.ops.splice(opStartOps, 0, this._writer.req2op({ type: 'varint', value: Varint64.from(blockIdCount) }));
        };
        /** @internal 是否该null值小于当做undefined编码 */
        Encoder.prototype._nullAsUndefined = function (value, type) {
            return value === null
                && this._options.nullAsUndefined
                && !SchemaUtil.canBeLiteral(type, null);
            // && SchemaUtil.canBeLiteral(type, undefined)  一定为true 因为先validate过了
        };
        Encoder.prototype._parseOverwrite = function (value, schema) {
            var skipFields = {};
            // 解引用
            var target = this._validator.protoHelper.parseReference(schema.target);
            var overwrite = this._validator.protoHelper.parseReference(schema.overwrite);
            var flatTarget = this._validator.protoHelper.getFlatInterfaceSchema(target);
            var flatOverwrite = this._validator.protoHelper.getFlatInterfaceSchema(overwrite);
            // 先区分哪些字段进入Target块，哪些字段进入Overwrite块
            var overwriteValue = {};
            var targetValue = {};
            // Overwrite块 property
            if (flatOverwrite.properties) {
                // 只要Overwrite中有此Property，即在Overwrite块编码
                for (var _i = 0, _a = flatOverwrite.properties; _i < _a.length; _i++) {
                    var property = _a[_i];
                    // undefined不编码，跳过SkipFIelds
                    if (value[property.name] !== undefined && !skipFields[property.name]) {
                        overwriteValue[property.name] = value[property.name];
                        skipFields[property.name] = 1;
                    }
                }
            }
            // Target块 property
            if (flatTarget.properties) {
                for (var _b = 0, _c = flatTarget.properties; _b < _c.length; _b++) {
                    var property = _c[_b];
                    // undefined不编码，跳过SkipFields
                    if (value[property.name] !== undefined && !skipFields[property.name]) {
                        targetValue[property.name] = value[property.name];
                        skipFields[property.name] = 1;
                    }
                }
            }
            // indexSignature
            var indexSignatureWriteValue; // indexSignature要写入的目标（overwrite或target）
            var indexSignature;
            // IndexSignature，优先使用Overwrite的
            if (flatOverwrite.indexSignature) {
                indexSignature = flatOverwrite.indexSignature;
                indexSignatureWriteValue = overwriteValue;
            }
            else if (flatTarget.indexSignature) {
                indexSignature = flatTarget.indexSignature;
                indexSignatureWriteValue = targetValue;
            }
            if (indexSignature) {
                for (var key in value) {
                    if (skipFields[key]) {
                        continue;
                    }
                    indexSignatureWriteValue[key] = value[key];
                    skipFields[key] = 1;
                }
            }
            // 编码，此处不再需要SkipFields，因为已经筛选过
            return {
                target: target,
                targetValue: targetValue,
                overwrite: overwrite,
                overwriteValue: overwriteValue
            };
        };
        Encoder.prototype._writeUnion = function (value, schema, skipFields, unionProperties) {
            // 计算unionProperties
            // if (!unionProperties) {
            //     unionProperties = skipFields ? Object.keys(skipFields) : [];
            // }
            // this._validator.protoHelper.getUnionProperties(schema).forEach(v => {
            //     unionProperties!.binaryInsert(v, true);
            // })
            if (skipFields === void 0) { skipFields = {}; }
            // 记住编码起点
            var encodeStartPos = this._writer.ops.length;
            var idNum = 0;
            // null as undefined
            if (this._nullAsUndefined(value, schema)) {
                value = undefined;
            }
            for (var _i = 0, _a = schema.members; _i < _a.length; _i++) {
                var member = _a[_i];
                // 验证该member是否可以编码            
                var vRes = this._validator.validate(value, member.type, {
                    // 禁用excessPropertyChecks（以代替unionProperties）
                    excessPropertyChecks: false,
                    // 启用strictNullChecks（null as undefined已经前置处理）
                    // strictNullChecks: true
                });
                if (vRes.isSucc) {
                    // 编码
                    // Part2: ID
                    this._writer.push({ type: 'varint', value: Varint64.from(member.id) });
                    var idPos = this._writer.ops.length - 1;
                    // Part3: Payload
                    if (member.type.type === 'Union') {
                        this._writeUnion(value, member.type, skipFields);
                    }
                    else {
                        this._write(value, member.type, {
                            skipFields: skipFields
                        });
                    }
                    idNum++;
                    this._processIdWithLengthType(idPos, member.type);
                    // 非object的value，类型一定互斥，只编码一个足矣
                    if (typeof value !== 'object') {
                        break;
                    }
                }
            }
            // 已经编码
            if (idNum > 0) {
                // 前置ID数量
                this._writer.ops.splice(encodeStartPos, 0, this._writer.req2op({ type: 'varint', value: Varint64.from(idNum) }));
                return;
            }
            else {
                // 未编码，没有任何条件满足，抛出异常
                throw new Error('Non member is satisfied for union type');
            }
        };
        Encoder.prototype._writeIntersection = function (value, schema, skipFields) {
            if (skipFields === void 0) { skipFields = {}; }
            // ID数量（member数量）
            this._writer.push({ type: 'varint', value: Varint64.from(schema.members.length) });
            // 按Member依次编码
            for (var _i = 0, _a = schema.members; _i < _a.length; _i++) {
                var member = _a[_i];
                // ID
                this._writer.push({ type: 'varint', value: Varint64.from(member.id) });
                var idPos = this._writer.ops.length - 1;
                // 编码块
                this._write(value, member.type, {
                    skipFields: skipFields
                });
                this._processIdWithLengthType(idPos, member.type);
            }
        };
        Encoder.prototype._writeBuffer = function (value) {
            // ArrayBuffer 转为Uint8Array
            if (value instanceof ArrayBuffer) {
                this._writer.push({ type: 'buffer', value: new Uint8Array(value) });
            }
            // Uint8Array 直接写入
            else if (value instanceof Uint8Array) {
                this._writer.push({ type: 'buffer', value: value });
            }
            // 其它TypedArray 转为Uint8Array
            else {
                var key = value.constructor.name;
                var arrType = TypedArrays[key];
                var uint8Arr = new Uint8Array(value.buffer, value.byteOffset, value.length * arrType.BYTES_PER_ELEMENT);
                this._writer.push({ type: 'buffer', value: uint8Arr });
            }
        };
        // private _writeIdBlocks(blocks: IDBlockItem[]) {
        //     // 字段数量: Varint
        //     this._writer.push({ type: 'varint', value: Varint64.from(blocks.length) });
        //     // 依次编码
        //     for (let item of blocks) {
        //         // ID
        //         this._writer.push({ type: 'varint', value: Varint64.from(item.id) });
        //         // Payload
        //         this._write(item.value, item.schema)
        //     }
        // }
        /**
         * 重新处理ID位，使其加入末位长度信息2Bit
         * @param idPos
         */
        Encoder.prototype._processIdWithLengthType = function (idPos, payloadType, lengthPrefixPos) {
            var idOp = this._writer.ops[idPos];
            if (idOp.type !== 'varint') {
                throw new Error('Error idPos: ' + idPos);
            }
            // 解引用
            var parsedSchema = this._validator.protoHelper.parseReference(payloadType);
            var lengthInfo = IdBlockUtil.getPayloadLengthInfo(parsedSchema, this._validator.protoHelper);
            var newId = (idOp.value.toNumber() << 2) + lengthInfo.lengthType;
            this._writer.ops[idPos] = this._writer.req2op({
                type: 'varint',
                value: Varint64.from(newId)
            });
            if (lengthInfo.needLengthPrefix) {
                var payloadByteLength = this._writer.ops.filter(function (v, i) { return i > idPos; }).sum(function (v) { return v.length; });
                this._writer.ops.splice(lengthPrefixPos == undefined ? idPos + 1 : lengthPrefixPos, 0, this._writer.req2op({
                    type: 'varint',
                    value: Varint64.from(payloadByteLength)
                }));
            }
        };
        return Encoder;
    }());

    /**
     * @public
     */
    var TSBuffer = /** @class */ (function () {
        function TSBuffer(proto, options) {
            /** @internal 默认配置 */
            this._options = {
                excessPropertyChecks: true,
                strictNullChecks: false,
                skipEncodeValidate: false,
                skipDecodeValidate: false,
                cloneProto: true,
            };
            // but `options.validatorOptions` has higher priority to validate process (don't affect encode)
            this._options = __assign(__assign({}, this._options), options);
            this._proto = this._options.cloneProto ? Object.merge({}, proto) : proto;
            Object.assign(this._proto, Object.merge({}, options === null || options === void 0 ? void 0 : options.customTypes));
            this._validator = new TSBufferValidator(this._proto, {
                excessPropertyChecks: this._options.excessPropertyChecks,
                strictNullChecks: this._options.strictNullChecks,
                cloneProto: false
            });
            this.validate = this._validator.validate.bind(this._validator);
            this.prune = this._validator.prune.bind(this._validator);
            this._encoder = new Encoder({
                validator: this._validator,
                // if !strictNullChecks, then encoder can convert null to undefined
                nullAsUndefined: !this._options.strictNullChecks
            });
            this._decoder = new Decoder({
                validator: this._validator,
                // if !strictNullChecks, then decoder can convert undefined to null
                undefinedAsNull: !this._options.strictNullChecks
            });
        }
        /**
         * 编码
         * @param value - 要编码的值
         * @param schemaOrId - Schema 或 SchemaID，例如`a/b.ts`下的`Test`类型，其ID为`a/b/Test`
         */
        TSBuffer.prototype.encode = function (value, schemaOrId, options) {
            var _a;
            var schema;
            if (typeof schemaOrId === 'string') {
                schema = this._proto[schemaOrId];
                if (!schema) {
                    return { isSucc: false, errMsg: "Cannot find schema\uFF1A ".concat(schemaOrId) };
                }
            }
            else {
                schema = schemaOrId;
            }
            // validate before encode
            if (!((_a = options === null || options === void 0 ? void 0 : options.skipValidate) !== null && _a !== void 0 ? _a : this._options.skipEncodeValidate)) {
                var vRes = this._validator.validate(value, schema, {
                    // 禁用excessPropertyChecks，因为不会编码excess property
                    excessPropertyChecks: false
                });
                if (!vRes.isSucc) {
                    return vRes;
                }
            }
            var buf;
            try {
                buf = this._encoder.encode(value, schema);
            }
            catch (e) {
                return { isSucc: false, errMsg: e.message };
            }
            return { isSucc: true, buf: buf };
        };
        /**
         * 解码
         * @param buf - 待解码的二进制数据
         * @param schemaOrId - Schema 或 SchemaID，例如`a/b.ts`下的`Test`类型，其ID为`a/b/Test`
         */
        TSBuffer.prototype.decode = function (buf, schemaOrId, options) {
            var _a;
            var schema;
            if (typeof schemaOrId === 'string') {
                schema = this._proto[schemaOrId];
                if (!schema) {
                    return { isSucc: false, errMsg: "Cannot find schema\uFF1A ".concat(schemaOrId), errPhase: undefined };
                }
            }
            else {
                schema = schemaOrId;
            }
            var value;
            try {
                value = this._decoder.decode(buf, schema);
            }
            catch (e) {
                return { isSucc: false, errMsg: e.message, errPhase: 'decode' };
            }
            if (!((_a = options === null || options === void 0 ? void 0 : options.skipValidate) !== null && _a !== void 0 ? _a : this._options.skipDecodeValidate)) {
                var vRes = this._validator.validate(value, schema);
                if (!vRes.isSucc) {
                    return __assign(__assign({}, vRes), { errPhase: 'validate' });
                }
            }
            return { isSucc: true, value: value };
        };
        /**
         * 编码为 JSON Object，根据协议将 JSON 不支持的格式（如 ArrayBuffer、Date、ObjectId）转换成 JSON 可传输的格式
         * @param value
         * @param schemaOrId
         * @param options
         */
        TSBuffer.prototype.encodeJSON = function (value, schemaOrId, options) {
            var _a;
            var schema;
            if (typeof schemaOrId === 'string') {
                schema = this._proto[schemaOrId];
                if (!schema) {
                    return { isSucc: false, errMsg: "Cannot find schema\uFF1A ".concat(schemaOrId) };
                }
            }
            else {
                schema = schemaOrId;
            }
            // validate before encode
            if (!((_a = options === null || options === void 0 ? void 0 : options.skipValidate) !== null && _a !== void 0 ? _a : this._options.skipEncodeValidate)) {
                var vRes = this._validator.prune(value, schema);
                if (!vRes.isSucc) {
                    return vRes;
                }
                value = vRes.pruneOutput;
            }
            // TODO schema 里没有 Buffer 和 Custom 的自动跳过
            var json;
            try {
                json = this._encoder.encodeJSON(value, schema);
            }
            catch (e) {
                return { isSucc: false, errMsg: e.message };
            }
            return { isSucc: true, json: json };
        };
        /**
         * 从 JSON Object 解码，根据协议将 ArrayBuffer、Date、ObjectId 等类型从 JSON 中还原
         * @param json - JSON Object (是 JSON 对象，而非 JSON 字符串)
         * @param schemaOrId
         * @param options
         */
        TSBuffer.prototype.decodeJSON = function (json, schemaOrId, options) {
            var _a;
            var schema;
            if (typeof schemaOrId === 'string') {
                schema = this._proto[schemaOrId];
                if (!schema) {
                    return { isSucc: false, errMsg: "Cannot find schema\uFF1A ".concat(schemaOrId), errPhase: undefined };
                }
            }
            else {
                schema = schemaOrId;
            }
            // TODO schema 里没有 Buffer 和 Custom 的自动跳过
            var value;
            try {
                value = this._decoder.decodeJSON(json, schema);
            }
            catch (e) {
                return { isSucc: false, errMsg: e.message, errPhase: 'decode' };
            }
            if (!((_a = options === null || options === void 0 ? void 0 : options.skipValidate) !== null && _a !== void 0 ? _a : this._options.skipDecodeValidate)) {
                var vRes = this._validator.prune(value, schema);
                if (!vRes.isSucc) {
                    vRes.errPhase = 'validate';
                    return vRes;
                }
                return { isSucc: true, value: vRes.pruneOutput };
            }
            return { isSucc: true, value: value };
        };
        return TSBuffer;
    }());

    /*!
     * TSRPC Base Client v2.1.15
     * -----------------------------------------
     * Copyright (c) Kingworks Corporation.
     * MIT License
     * https://github.com/k8w/tsrpc-base-client
     */

    /**
     * An auto-increment counter
     */
    var Counter = /** @class */ (function () {
        function Counter(min, max) {
            if (min === void 0) { min = 1; }
            if (max === void 0) { max = Number.MAX_SAFE_INTEGER; }
            this._min = min;
            this._max = max;
            this._last = max;
        }
        /**
         * Reset the counter, makes `getNext()` restart from `0`
         */
        Counter.prototype.reset = function () {
            this._last = this._max;
        };
        /**
         * Get next counter value, and auto increment `1`
         * @param notInc - Just get the next possible value, not actually increasing the sequence
         */
        Counter.prototype.getNext = function (notInc) {
            return this._last >= this._max ? (this._last = this._min) : (notInc ? this._last : ++this._last);
        };
        Object.defineProperty(Counter.prototype, "last", {
            /**
             * Last return of `getNext()`
             */
            get: function () {
                return this._last;
            },
            enumerable: false,
            configurable: true
        });
        return Counter;
    }());

    /**
     * A `Flow` is consists of many `FlowNode`, which is function with the same input and output (like pipeline).
     *
     * @remarks
     * `Flow` is like a hook or event, executed at a specific time.
     * The difference to event is it can be used to **interrupt** an action, by return `undefined` or `null` in a node.
     */
    var Flow = /** @class */ (function () {
        function Flow() {
            /**
             * All node functions, if you want to adjust the sort you can modify this.
             */
            this.nodes = [];
            /**
             * Event when error throwed from a `FlowNode` function.
             * By default, it does nothing except print a `Uncaught FlowError` error log.
             * @param e
             * @param last
             * @param input
             * @param logger
             */
            this.onError = function (e, last, input, logger) {
                logger === null || logger === void 0 ? void 0 : logger.error('Uncaught FlowError:', e);
            };
        }
        /**
         * Execute all node function one by one, the previous output is the next input,
         * until the last output would be return to the caller.
         *
         * @remarks
         * If any node function return `null | undefined`, or throws an error,
         * the latter node functions would not be executed.
         * And it would return `null | undefined` immediately to the caller,
         * which tell the caller it means a interruption,
         * to let the caller stop latter behaviours.
         *
         * @param input The input of the first `FlowNode`
         * @param logger Logger to print log, `undefined` means to hide all log.
         * @returns
         */
        Flow.prototype.exec = function (input, logger) {
            return __awaiter(this, void 0, void 0, function () {
                var res, i, e_1;
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            res = input;
                            i = 0;
                            _a.label = 1;
                        case 1:
                            if (!(i < this.nodes.length)) return [3 /*break*/, 7];
                            _a.label = 2;
                        case 2:
                            _a.trys.push([2, 4, , 5]);
                            return [4 /*yield*/, this.nodes[i](res)];
                        case 3:
                            res = _a.sent();
                            return [3 /*break*/, 5];
                        case 4:
                            e_1 = _a.sent();
                            this.onError(e_1, res, input, logger);
                            return [2 /*return*/, undefined];
                        case 5:
                            // Return 非true 表示不继续后续流程 立即中止
                            if (res === null || res === undefined) {
                                return [2 /*return*/, res];
                            }
                            _a.label = 6;
                        case 6:
                            ++i;
                            return [3 /*break*/, 1];
                        case 7: return [2 /*return*/, res];
                    }
                });
            });
        };
        /**
         * Append a node function to the last
         * @param node
         * @returns
         */
        Flow.prototype.push = function (node) {
            this.nodes.push(node);
            return node;
        };
        /**
         * Remove a node function
         * @param node
         * @returns
         */
        Flow.prototype.remove = function (node) {
            return this.nodes.remove(function (v) { return v === node; });
        };
        return Flow;
    }());

    function getCustomObjectIdTypes(classObjectId) {
        var output = {};
        // string
        if (classObjectId === String) {
            output['?mongodb/ObjectId'] = {
                type: SchemaType.Custom,
                validate: function (value) {
                    if (typeof value !== 'string') {
                        return { isSucc: false, errMsg: "Expected type to be `string`, actually `".concat(typeof value, "`.") };
                    }
                    if (!/^[0-9a-fA-F]{24}$/.test(value)) {
                        return { isSucc: false, errMsg: 'ObjectId must be a string of 24 hex characters' };
                    }
                    return { isSucc: true };
                },
                encode: function (value) {
                    return new Uint8Array(Array.from({ length: 12 }, function (_, i) { return Number.parseInt('0x' + value.substr(i * 2, 2)); }));
                },
                decode: function (buf) {
                    return Array.from(buf, function (v) {
                        var str = v.toString(16);
                        if (str.length === 1) {
                            str = '0' + str;
                        }
                        return str;
                    }).join('');
                }
            };
        }
        // ObjectId
        else {
            output['?mongodb/ObjectId'] = {
                type: SchemaType.Custom,
                validate: function (value) { return (value instanceof classObjectId) ?
                    { isSucc: true } :
                    { isSucc: false, errMsg: "Expected to be instance of `ObjectId`, actually not." }; },
                encode: function (value) { return new Uint8Array(value.id); },
                decode: function (buf) { return new classObjectId(buf); },
                decodeJSON: function (json) { return new classObjectId(json); }
            };
        }
        output['?mongodb/ObjectID'] = output['?mongodb/ObjectId'];
        output['?bson/ObjectId'] = output['?mongodb/ObjectId'];
        output['?bson/ObjectID'] = output['?mongodb/ObjectId'];
        return output;
    }

    /**
     * A manager for TSRPC receiving messages
     */
    var MsgHandlerManager = /** @class */ (function () {
        function MsgHandlerManager() {
            this._handlers = {};
        }
        /**
         * Execute all handlers parallelly
         * @returns handlers count
         */
        MsgHandlerManager.prototype.forEachHandler = function (msgName, logger) {
            var args = [];
            for (var _i = 2; _i < arguments.length; _i++) {
                args[_i - 2] = arguments[_i];
            }
            var handlers = this._handlers[msgName];
            if (!handlers) {
                return [];
            }
            var output = [];
            for (var _a = 0, handlers_1 = handlers; _a < handlers_1.length; _a++) {
                var handler = handlers_1[_a];
                try {
                    output.push(handler.apply(void 0, args));
                }
                catch (e) {
                    logger === null || logger === void 0 ? void 0 : logger.error('[MsgHandlerError]', e);
                }
            }
            return output;
        };
        /**
         * Add message handler, duplicate handlers to the same `msgName` would be ignored.
         * @param msgName
         * @param handler
         * @returns
         */
        MsgHandlerManager.prototype.addHandler = function (msgName, handler) {
            var handlers = this._handlers[msgName];
            // 初始化Handlers
            if (!handlers) {
                handlers = this._handlers[msgName] = [];
            }
            // 防止重复监听
            else if (handlers.some(function (v) { return v === handler; })) {
                return;
            }
            handlers.push(handler);
        };
        /**
         * Remove handler from the specific `msgName`
         * @param msgName
         * @param handler
         * @returns
         */
        MsgHandlerManager.prototype.removeHandler = function (msgName, handler) {
            var handlers = this._handlers[msgName];
            if (!handlers) {
                return;
            }
            handlers.removeOne(function (v) { return v === handler; });
        };
        /**
         * Remove all handlers for the specific `msgName`
         * @param msgName
         */
        MsgHandlerManager.prototype.removeAllHandlers = function (msgName) {
            this._handlers[msgName] = undefined;
        };
        return MsgHandlerManager;
    }());

    /** A utility for generate `ServiceMap` */
    var ServiceMapUtil = /** @class */ (function () {
        function ServiceMapUtil() {
        }
        ServiceMapUtil.getServiceMap = function (proto) {
            var map = {
                id2Service: {},
                apiName2Service: {},
                msgName2Service: {}
            };
            for (var _i = 0, _a = proto.services; _i < _a.length; _i++) {
                var v = _a[_i];
                var match = v.name.match(/(.+\/)?([^\/]+)$/);
                var path = match[1] || '';
                var name_1 = match[2];
                if (v.type === 'api') {
                    var svc = __assign(__assign({}, v), { reqSchemaId: "".concat(path, "Ptl").concat(name_1, "/Req").concat(name_1), resSchemaId: "".concat(path, "Ptl").concat(name_1, "/Res").concat(name_1) });
                    map.apiName2Service[v.name] = svc;
                    map.id2Service[v.id] = svc;
                }
                else {
                    var svc = __assign(__assign({}, v), { msgSchemaId: "".concat(path, "Msg").concat(name_1, "/Msg").concat(name_1) });
                    map.msgName2Service[v.name] = svc;
                    map.id2Service[v.id] = svc;
                }
            }
            return map;
        };
        return ServiceMapUtil;
    }());

    var TransportDataUtil = /** @class */ (function () {
        function TransportDataUtil() {
        }
        Object.defineProperty(TransportDataUtil, "tsbuffer", {
            get: function () {
                if (!this._tsbuffer) {
                    this._tsbuffer = new TSBuffer(TransportDataProto);
                }
                return this._tsbuffer;
            },
            enumerable: false,
            configurable: true
        });
        TransportDataUtil.encodeClientMsg = function (tsbuffer, service, msg, type, connType) {
            if (type === 'buffer') {
                var op = tsbuffer.encode(msg, service.msgSchemaId);
                if (!op.isSucc) {
                    return op;
                }
                var serverInputData = {
                    serviceId: service.id,
                    buffer: op.buf
                };
                var opOut = this.tsbuffer.encode(serverInputData, 'ServerInputData');
                return opOut.isSucc ? { isSucc: true, output: opOut.buf } : { isSucc: false, errMsg: opOut.errMsg };
            }
            else {
                var op = tsbuffer.encodeJSON(msg, service.msgSchemaId);
                if (!op.isSucc) {
                    return op;
                }
                var json = connType === 'SHORT' ? op.json : [service.name, op.json];
                return { isSucc: true, output: type === 'json' ? json : JSON.stringify(json) };
            }
        };
        TransportDataUtil.encodeApiReq = function (tsbuffer, service, req, type, sn) {
            if (type === 'buffer') {
                var op = tsbuffer.encode(req, service.reqSchemaId);
                if (!op.isSucc) {
                    return op;
                }
                var serverInputData = {
                    serviceId: service.id,
                    buffer: op.buf,
                    sn: sn
                };
                var opOut = this.tsbuffer.encode(serverInputData, 'ServerInputData');
                return opOut.isSucc ? { isSucc: true, output: opOut.buf } : { isSucc: false, errMsg: opOut.errMsg };
            }
            else {
                var op = tsbuffer.encodeJSON(req, service.reqSchemaId);
                if (!op.isSucc) {
                    return op;
                }
                var json = sn === undefined ? op.json : [service.name, op.json, sn];
                return { isSucc: true, output: type === 'json' ? json : JSON.stringify(json) };
            }
        };
        TransportDataUtil.encodeServerMsg = function (tsbuffer, service, msg, type, connType) {
            if (type === 'buffer') {
                var op = tsbuffer.encode(msg, service.msgSchemaId);
                if (!op.isSucc) {
                    return op;
                }
                var serverOutputData = {
                    serviceId: service.id,
                    buffer: op.buf
                };
                var opOut = this.tsbuffer.encode(serverOutputData, 'ServerOutputData');
                return opOut.isSucc ? { isSucc: true, output: opOut.buf } : { isSucc: false, errMsg: opOut.errMsg };
            }
            else {
                var op = tsbuffer.encodeJSON(msg, service.msgSchemaId);
                if (!op.isSucc) {
                    return op;
                }
                var json = connType === 'SHORT' ? op.json : [service.name, op.json];
                return { isSucc: true, output: type === 'json' ? json : JSON.stringify(json) };
            }
        };
        TransportDataUtil.parseServerOutout = function (tsbuffer, serviceMap, data, serviceId) {
            if (data instanceof Uint8Array) {
                var opServerOutputData = this.tsbuffer.decode(data, 'ServerOutputData');
                if (!opServerOutputData.isSucc) {
                    return opServerOutputData;
                }
                var serverOutputData = opServerOutputData.value;
                serviceId = serviceId !== null && serviceId !== void 0 ? serviceId : serverOutputData.serviceId;
                if (serviceId === undefined) {
                    return { isSucc: false, errMsg: "Missing 'serviceId' in ServerOutput" };
                }
                var service = serviceMap.id2Service[serviceId];
                if (!service) {
                    return { isSucc: false, errMsg: "Invalid service ID: ".concat(serviceId, " (from ServerOutput)") };
                }
                if (service.type === 'msg') {
                    if (!serverOutputData.buffer) {
                        return { isSucc: false, errMsg: 'Empty msg buffer (from ServerOutput)' };
                    }
                    var opMsg = tsbuffer.decode(serverOutputData.buffer, service.msgSchemaId);
                    if (!opMsg.isSucc) {
                        return opMsg;
                    }
                    return {
                        isSucc: true,
                        result: {
                            type: 'msg',
                            service: service,
                            msg: opMsg.value
                        }
                    };
                }
                else {
                    if (serverOutputData.error) {
                        return {
                            isSucc: true,
                            result: {
                                type: 'api',
                                service: service,
                                sn: serverOutputData.sn,
                                ret: {
                                    isSucc: false,
                                    err: new TsrpcError(serverOutputData.error)
                                }
                            }
                        };
                    }
                    else {
                        if (!serverOutputData.buffer) {
                            return { isSucc: false, errMsg: 'Empty API res buffer (from ServerOutput)' };
                        }
                        var opRes = tsbuffer.decode(serverOutputData.buffer, service.resSchemaId);
                        if (!opRes.isSucc) {
                            return opRes;
                        }
                        return {
                            isSucc: true,
                            result: {
                                type: 'api',
                                service: service,
                                sn: serverOutputData.sn,
                                ret: {
                                    isSucc: true,
                                    res: opRes.value,
                                }
                            }
                        };
                    }
                }
            }
            else {
                var json = void 0;
                if (typeof data === 'string') {
                    try {
                        json = JSON.parse(data);
                    }
                    catch (e) {
                        return { isSucc: false, errMsg: "Invalid input JSON: ".concat(e.message) };
                    }
                }
                else {
                    json = data;
                }
                var body = void 0;
                var sn = void 0;
                var service = void 0;
                if (serviceId == undefined) {
                    if (!Array.isArray(json)) {
                        return { isSucc: false, errMsg: "Invalid server output format" };
                    }
                    var serviceName = json[0];
                    body = json[1];
                    sn = json[2];
                    // 有 SN 是 Api，没 SN 是 Msg
                    service = sn ? serviceMap.apiName2Service[serviceName] : serviceMap.msgName2Service[serviceName];
                    if (!service) {
                        return { isSucc: false, errMsg: "Invalid service name: ".concat(serviceName, " (from ServerOutputData)") };
                    }
                }
                else {
                    service = serviceMap.id2Service[serviceId];
                    if (!service) {
                        return { isSucc: false, errMsg: "Invalid service ID: ".concat(serviceId) };
                    }
                    body = json;
                }
                if (service.type === 'api') {
                    if (body.isSucc && 'res' in body) {
                        var op = tsbuffer.decodeJSON(body.res, service.resSchemaId);
                        if (!op.isSucc) {
                            return op;
                        }
                        body.res = op.value;
                    }
                    else if (body.err) {
                        body.err = new TsrpcError(body.err);
                    }
                    else {
                        return { isSucc: false, errMsg: "Invalid server output format" };
                    }
                    return {
                        isSucc: true,
                        result: {
                            type: 'api',
                            service: service,
                            sn: sn,
                            ret: body
                        }
                    };
                }
                else {
                    var op = tsbuffer.decodeJSON(body, service.msgSchemaId);
                    if (!op.isSucc) {
                        return op;
                    }
                    return {
                        isSucc: true,
                        result: {
                            type: 'msg',
                            service: service,
                            msg: op.value
                        }
                    };
                }
            }
        };
        // 心跳包（Ping & Pong），所有开头为 0 的 Buffer，均为控制指令
        TransportDataUtil.HeartbeatPacket = new Uint8Array([0]);
        return TransportDataUtil;
    }());

    /**
     * An abstract base class for TSRPC Client,
     * which includes some common buffer process flows.
     *
     * @remarks
     * You can implement a client on a specific transportation protocol (like HTTP, WebSocket, QUIP) by extend this.
     *
     * @typeParam ServiceType - `ServiceType` from generated `proto.ts`
     *
     * @see
     * {@link https://github.com/k8w/tsrpc}
     * {@link https://github.com/k8w/tsrpc-browser}
     * {@link https://github.com/k8w/tsrpc-miniapp}
     */
    var BaseClient = /** @class */ (function () {
        function BaseClient(proto, options) {
            this._msgHandlers = new MsgHandlerManager();
            /**
             * {@link Flow} to process `callApi`, `sendMsg`, buffer input/output, etc...
             */
            this.flows = {
                // callApi
                preCallApiFlow: new Flow(),
                preApiReturnFlow: new Flow(),
                postApiReturnFlow: new Flow(),
                // sendMsg
                preSendMsgFlow: new Flow(),
                postSendMsgFlow: new Flow(),
                preRecvMsgFlow: new Flow(),
                postRecvMsgFlow: new Flow(),
                // buffer
                preSendDataFlow: new Flow(),
                preRecvDataFlow: new Flow(),
                /**
                 * @deprecated Please use `preSendDataFlow` instead
                 */
                preSendBufferFlow: new Flow(),
                /**
                 * @deprecated Please use `preRecvDataFlow` instead
                 */
                preRecvBufferFlow: new Flow(),
                // Connection Flows (Only for WebSocket)
                /** Before connect to WebSocket server */
                preConnectFlow: new Flow(),
                /** After WebSocket connect successfully */
                postConnectFlow: new Flow(),
                /** After WebSocket disconnected (from connected status) */
                postDisconnectFlow: new Flow(),
            };
            this._apiSnCounter = new Counter(1);
            /**
             * Pending API Requests
             */
            this._pendingApis = [];
            /** @deprecated Please use `_onRecvData` instead */
            this._onRecvBuf = this._onRecvData;
            this.options = options;
            this.serviceMap = ServiceMapUtil.getServiceMap(proto);
            this.dataType = this.options.json ? 'text' : 'buffer';
            var types = __assign({}, proto.types);
            // Custom ObjectId handler
            if (options.customObjectIdClass) {
                types = __assign(__assign({}, types), getCustomObjectIdTypes(options.customObjectIdClass));
            }
            this.tsbuffer = new TSBuffer(types);
            this.logger = this.options.logger;
            if (this.logger) {
                this.logger = setLogLevel(this.logger, this.options.logLevel);
            }
        }
        Object.defineProperty(BaseClient.prototype, "lastSN", {
            /**
             * The `SN` number of the last `callApi()`,
             * which can be passed to `abort()` to abort an API request.
             * @example
             * ```ts
             * client.callApi('xxx', { value: 'xxx' })
             *   .then(ret=>{ console.log('succ', ret) });
             * let lastSN = client.lastSN;
             * client.abort(lastSN);
             * ```
             */
            get: function () {
                return this._apiSnCounter.last;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(BaseClient.prototype, "nextSN", {
            /**
             * The `SN` number of the next `callApi()`,
             * which can be passed to `abort()` to abort an API request.
             * @example
             * ```ts
             * let nextSN = client.nextSN;
             * client.callApi('xxx', { value: 'xxx' })
             * ```
             */
            get: function () {
                return this._apiSnCounter.getNext(true);
            },
            enumerable: false,
            configurable: true
        });
        /**
         * Send request and wait for the return
         * @param apiName
         * @param req - Request body
         * @param options - Transport options
         * @returns return a `ApiReturn`, all error (network error, business error, code exception...) is unified as `TsrpcError`.
         * The promise is never rejected, so you just need to process all error in one place.
         */
        BaseClient.prototype.callApi = function (apiName, req, options) {
            if (options === void 0) { options = {}; }
            return __awaiter(this, void 0, void 0, function () {
                var sn, pendingItem, promise;
                var _this = this;
                return __generator(this, function (_a) {
                    sn = this._apiSnCounter.getNext();
                    pendingItem = {
                        sn: sn,
                        abortKey: options.abortKey,
                        service: this.serviceMap.apiName2Service[apiName]
                    };
                    this._pendingApis.push(pendingItem);
                    promise = new Promise(function (rs) { return __awaiter(_this, void 0, void 0, function () {
                        var pre, ret, preReturn;
                        var _a, _b;
                        return __generator(this, function (_c) {
                            switch (_c.label) {
                                case 0: return [4 /*yield*/, this.flows.preCallApiFlow.exec({
                                        apiName: apiName,
                                        req: req,
                                        options: options
                                    }, this.logger)];
                                case 1:
                                    pre = _c.sent();
                                    if (!pre || pendingItem.isAborted) {
                                        this.abort(pendingItem.sn);
                                        return [2 /*return*/];
                                    }
                                    if (!pre.return) return [3 /*break*/, 2];
                                    ret = pre.return;
                                    return [3 /*break*/, 4];
                                case 2: return [4 /*yield*/, this._doCallApi(pre.apiName, pre.req, pre.options, pendingItem)];
                                case 3:
                                    // do call means it will send buffer via network
                                    ret = _c.sent();
                                    _c.label = 4;
                                case 4:
                                    if (pendingItem.isAborted) {
                                        return [2 /*return*/];
                                    }
                                    // Log Original Return
                                    if (ret.isSucc) {
                                        this.options.logApi && ((_a = this.logger) === null || _a === void 0 ? void 0 : _a.log("[ApiRes] #".concat(pendingItem.sn, " ").concat(apiName), ret.res));
                                    }
                                    else {
                                        this.options.logApi && ((_b = this.logger) === null || _b === void 0 ? void 0 : _b[ret.err.type === TsrpcError.Type.ApiError ? 'log' : 'error']("[ApiErr] #".concat(pendingItem.sn, " ").concat(apiName), ret.err));
                                    }
                                    return [4 /*yield*/, this.flows.preApiReturnFlow.exec(__assign(__assign({}, pre), { return: ret }), this.logger)];
                                case 5:
                                    preReturn = _c.sent();
                                    if (!preReturn) {
                                        this.abort(pendingItem.sn);
                                        return [2 /*return*/];
                                    }
                                    rs(preReturn.return);
                                    // Post Flow
                                    this.flows.postApiReturnFlow.exec(preReturn, this.logger);
                                    return [2 /*return*/];
                            }
                        });
                    }); });
                    // Finally clear pendings
                    promise.catch().then(function () {
                        _this._pendingApis.removeOne(function (v) { return v.sn === pendingItem.sn; });
                    });
                    return [2 /*return*/, promise];
                });
            });
        };
        BaseClient.prototype._doCallApi = function (apiName, req, options, pendingItem) {
            var _a;
            if (options === void 0) { options = {}; }
            return __awaiter(this, void 0, void 0, function () {
                var promise;
                var _this = this;
                return __generator(this, function (_b) {
                    this.options.logApi && ((_a = this.logger) === null || _a === void 0 ? void 0 : _a.log("[ApiReq] #".concat(pendingItem.sn), apiName, req));
                    promise = new Promise(function (rs) { return __awaiter(_this, void 0, void 0, function () {
                        var service, opEncode, promiseReturn, promiseSend, opSend, ret;
                        var _a;
                        return __generator(this, function (_b) {
                            switch (_b.label) {
                                case 0:
                                    service = this.serviceMap.apiName2Service[apiName];
                                    if (!service) {
                                        rs({
                                            isSucc: false,
                                            err: new TsrpcError('Invalid api name: ' + apiName, {
                                                code: 'INVALID_API_NAME',
                                                type: exports.TsrpcErrorType.ClientError
                                            })
                                        });
                                        return [2 /*return*/];
                                    }
                                    pendingItem.service = service;
                                    opEncode = TransportDataUtil.encodeApiReq(this.tsbuffer, service, req, this.dataType, this.type === 'LONG' ? pendingItem.sn : undefined);
                                    if (!opEncode.isSucc) {
                                        rs({
                                            isSucc: false, err: new TsrpcError(opEncode.errMsg, {
                                                type: exports.TsrpcErrorType.ClientError,
                                                code: 'INPUT_DATA_ERR'
                                            })
                                        });
                                        return [2 /*return*/];
                                    }
                                    promiseReturn = this._waitApiReturn(pendingItem, (_a = options.timeout) !== null && _a !== void 0 ? _a : this.options.timeout);
                                    promiseSend = this.sendData(opEncode.output, options, service.id, pendingItem);
                                    return [4 /*yield*/, promiseSend];
                                case 1:
                                    opSend = _b.sent();
                                    if (opSend.err) {
                                        rs({
                                            isSucc: false,
                                            err: opSend.err
                                        });
                                        return [2 /*return*/];
                                    }
                                    return [4 /*yield*/, promiseReturn];
                                case 2:
                                    ret = _b.sent();
                                    if (pendingItem.isAborted) {
                                        return [2 /*return*/];
                                    }
                                    rs(ret);
                                    return [2 /*return*/];
                            }
                        });
                    }); });
                    return [2 /*return*/, promise];
                });
            });
        };
        /**
         * Send message, without response, not ensuring the server is received and processed correctly.
         * @param msgName
         * @param msg - Message body
         * @param options - Transport options
         * @returns If the promise is resolved, it means the request is sent to system kernel successfully.
         * Notice that not means the server received and processed the message correctly.
         */
        BaseClient.prototype.sendMsg = function (msgName, msg, options) {
            var _this = this;
            if (options === void 0) { options = {}; }
            var promise = new Promise(function (rs) { return __awaiter(_this, void 0, void 0, function () {
                var pre, service, opEncode, promiseSend, opSend;
                var _a, _b;
                return __generator(this, function (_c) {
                    switch (_c.label) {
                        case 0: return [4 /*yield*/, this.flows.preSendMsgFlow.exec({
                                msgName: msgName,
                                msg: msg,
                                options: options
                            }, this.logger)];
                        case 1:
                            pre = _c.sent();
                            if (!pre) {
                                return [2 /*return*/];
                            }
                            // The msg is not prevented by pre flow
                            this.options.logMsg && ((_a = this.logger) === null || _a === void 0 ? void 0 : _a.log("[SendMsg]", msgName, msg));
                            service = this.serviceMap.msgName2Service[msgName];
                            if (!service) {
                                (_b = this.logger) === null || _b === void 0 ? void 0 : _b.error('Invalid msg name: ' + msgName);
                                rs({
                                    isSucc: false,
                                    err: new TsrpcError('Invalid msg name: ' + msgName, {
                                        code: 'INVALID_MSG_NAME',
                                        type: exports.TsrpcErrorType.ClientError
                                    })
                                });
                                return [2 /*return*/];
                            }
                            opEncode = TransportDataUtil.encodeClientMsg(this.tsbuffer, service, msg, this.dataType, this.type);
                            if (!opEncode.isSucc) {
                                rs({
                                    isSucc: false,
                                    err: new TsrpcError(opEncode.errMsg, {
                                        type: exports.TsrpcErrorType.ClientError,
                                        code: 'ENCODE_MSG_ERR'
                                    })
                                });
                                return [2 /*return*/];
                            }
                            promiseSend = this.sendData(opEncode.output, options, service.id);
                            return [4 /*yield*/, promiseSend];
                        case 2:
                            opSend = _c.sent();
                            if (opSend.err) {
                                rs({
                                    isSucc: false,
                                    err: opSend.err
                                });
                                return [2 /*return*/];
                            }
                            rs({ isSucc: true });
                            // Post Flow
                            this.flows.postSendMsgFlow.exec(pre, this.logger);
                            return [2 /*return*/];
                    }
                });
            }); });
            promise.then(function (v) {
                var _a;
                if (!v.isSucc) {
                    ((_a = _this.logger) !== null && _a !== void 0 ? _a : console).error('[SendMsgErr]', v.err);
                }
            });
            return promise;
        };
        /**
         * Add a message handler,
         * duplicate handlers to the same `msgName` would be ignored.
         * @param msgName
         * @param handler
         * @returns
         */
        // listenMsg<T extends keyof ServiceType['msg']>(msgName: T, handler: ClientMsgHandler<ServiceType, T, this>): ClientMsgHandler<ServiceType, T, this>;
        // listenMsg(msgName: RegExp, handler: ClientMsgHandler<ServiceType, keyof ServiceType['msg'], this>): ClientMsgHandler<ServiceType, keyof ServiceType['msg'], this>;
        // listenMsg(msgName: string | RegExp, handler: ClientMsgHandler<ServiceType, string, this>): ClientMsgHandler<ServiceType, string, this> {
        BaseClient.prototype.listenMsg = function (msgName, handler) {
            var _this = this;
            if (msgName instanceof RegExp) {
                Object.keys(this.serviceMap.msgName2Service).filter(function (k) { return msgName.test(k); }).forEach(function (k) {
                    _this._msgHandlers.addHandler(k, handler);
                });
            }
            else {
                this._msgHandlers.addHandler(msgName, handler);
            }
            return handler;
        };
        /**
         * Remove a message handler
         */
        BaseClient.prototype.unlistenMsg = function (msgName, handler) {
            var _this = this;
            if (msgName instanceof RegExp) {
                Object.keys(this.serviceMap.msgName2Service).filter(function (k) { return msgName.test(k); }).forEach(function (k) {
                    _this._msgHandlers.removeHandler(k, handler);
                });
            }
            else {
                this._msgHandlers.removeHandler(msgName, handler);
            }
        };
        /**
         * Remove all handlers from a message
         */
        BaseClient.prototype.unlistenMsgAll = function (msgName) {
            var _this = this;
            if (msgName instanceof RegExp) {
                Object.keys(this.serviceMap.msgName2Service).filter(function (k) { return msgName.test(k); }).forEach(function (k) {
                    _this._msgHandlers.removeAllHandlers(k);
                });
            }
            else {
                this._msgHandlers.removeAllHandlers(msgName);
            }
        };
        /**
         * Abort a pending API request, it makes the promise returned by `callApi()` neither resolved nor rejected forever.
         * @param sn - Every api request has a unique `sn` number, you can get it by `this.lastSN`
         */
        BaseClient.prototype.abort = function (sn) {
            var _a, _b;
            // Find
            var index = this._pendingApis.findIndex(function (v) { return v.sn === sn; });
            if (index === -1) {
                return;
            }
            var pendingItem = this._pendingApis[index];
            // Clear
            this._pendingApis.splice(index, 1);
            pendingItem.onReturn = undefined;
            pendingItem.isAborted = true;
            // Log
            (_a = this.logger) === null || _a === void 0 ? void 0 : _a.log("[ApiAbort] #".concat(pendingItem.sn, " ").concat(pendingItem.service.name));
            // onAbort
            (_b = pendingItem.onAbort) === null || _b === void 0 ? void 0 : _b.call(pendingItem);
        };
        /**
         * Abort all API requests that has the `abortKey`.
         * It makes the promise returned by `callApi` neither resolved nor rejected forever.
         * @param abortKey - The `abortKey` of options when `callApi()`, see {@link TransportOptions.abortKey}.
         * @example
         * ```ts
         * // Send API request many times
         * client.callApi('SendData', { data: 'AAA' }, { abortKey: 'Session#123' });
         * client.callApi('SendData', { data: 'BBB' }, { abortKey: 'Session#123' });
         * client.callApi('SendData', { data: 'CCC' }, { abortKey: 'Session#123' });
         *
         * // And abort the at once
         * client.abortByKey('Session#123');
         * ```
         */
        BaseClient.prototype.abortByKey = function (abortKey) {
            var _this = this;
            this._pendingApis.filter(function (v) { return v.abortKey === abortKey; }).forEach(function (v) { _this.abort(v.sn); });
        };
        /**
         * Abort all pending API requests.
         * It makes the promise returned by `callApi` neither resolved nor rejected forever.
         */
        BaseClient.prototype.abortAll = function () {
            var _this = this;
            this._pendingApis.slice().forEach(function (v) { return _this.abort(v.sn); });
        };
        /**
         * Send data (binary or text)
         * @remarks
         * Long connection: wait res by listenning `conn.onmessage`
         * Short connection: wait res by waitting response
         * @param data
         * @param options
         * @param sn
         */
        BaseClient.prototype.sendData = function (data, options, serviceId, pendingApiItem) {
            var _a, _b, _c;
            return __awaiter(this, void 0, void 0, function () {
                var pre, preBuf;
                return __generator(this, function (_d) {
                    switch (_d.label) {
                        case 0: return [4 /*yield*/, this.flows.preSendDataFlow.exec({ data: data, sn: pendingApiItem === null || pendingApiItem === void 0 ? void 0 : pendingApiItem.sn }, this.logger)];
                        case 1:
                            pre = _d.sent();
                            if (!pre) {
                                return [2 /*return*/, new Promise(function (rs) { })];
                            }
                            data = pre.data;
                            if (!(data instanceof Uint8Array)) return [3 /*break*/, 3];
                            return [4 /*yield*/, this.flows.preSendBufferFlow.exec({ buf: data, sn: pendingApiItem === null || pendingApiItem === void 0 ? void 0 : pendingApiItem.sn }, this.logger)];
                        case 2:
                            preBuf = _d.sent();
                            if (!preBuf) {
                                return [2 /*return*/, new Promise(function (rs) { })];
                            }
                            data = preBuf.buf;
                            _d.label = 3;
                        case 3:
                            // debugBuf log
                            if (this.options.debugBuf) {
                                if (typeof data === 'string') {
                                    (_a = this.logger) === null || _a === void 0 ? void 0 : _a.debug('[SendText]' + (pendingApiItem ? (' #' + pendingApiItem.sn) : '') + " length=".concat(data.length), data);
                                }
                                else if (data instanceof Uint8Array) {
                                    (_b = this.logger) === null || _b === void 0 ? void 0 : _b.debug('[SendBuf]' + (pendingApiItem ? (' #' + pendingApiItem.sn) : '') + " length=".concat(data.length), data);
                                }
                                else {
                                    (_c = this.logger) === null || _c === void 0 ? void 0 : _c.debug('[SendJSON]' + (pendingApiItem ? (' #' + pendingApiItem.sn) : ''), data);
                                }
                            }
                            return [2 /*return*/, this._sendData(data, options, serviceId, pendingApiItem)];
                    }
                });
            });
        };
        // 信道可传输二进制或字符串
        BaseClient.prototype._onRecvData = function (data, pendingApiItem) {
            var _a, _b, _c, _d, _e, _f, _g, _h, _j;
            return __awaiter(this, void 0, void 0, function () {
                var sn, pre, pre_1, opParsed, parsed, pre_2;
                return __generator(this, function (_k) {
                    switch (_k.label) {
                        case 0:
                            sn = pendingApiItem === null || pendingApiItem === void 0 ? void 0 : pendingApiItem.sn;
                            return [4 /*yield*/, this.flows.preRecvDataFlow.exec({ data: data, sn: sn }, this.logger)];
                        case 1:
                            pre = _k.sent();
                            if (!pre) {
                                return [2 /*return*/];
                            }
                            data = pre.data;
                            if (!(typeof data === 'string')) return [3 /*break*/, 2];
                            this.options.debugBuf && ((_a = this.logger) === null || _a === void 0 ? void 0 : _a.debug('[RecvText]' + (sn ? (' #' + sn) : ''), data));
                            return [3 /*break*/, 5];
                        case 2:
                            if (!(data instanceof Uint8Array)) return [3 /*break*/, 4];
                            this.options.debugBuf && ((_b = this.logger) === null || _b === void 0 ? void 0 : _b.debug('[RecvBuf]' + (sn ? (' #' + sn) : ''), 'length=' + data.length, data));
                            return [4 /*yield*/, this.flows.preRecvBufferFlow.exec({ buf: data, sn: sn }, this.logger)];
                        case 3:
                            pre_1 = _k.sent();
                            if (!pre_1) {
                                return [2 /*return*/];
                            }
                            data = pre_1.buf;
                            return [3 /*break*/, 5];
                        case 4:
                            this.options.debugBuf && ((_c = this.logger) === null || _c === void 0 ? void 0 : _c.debug('[RecvJSON]' + (sn ? (' #' + sn) : ''), data));
                            _k.label = 5;
                        case 5:
                            opParsed = TransportDataUtil.parseServerOutout(this.tsbuffer, this.serviceMap, data, pendingApiItem === null || pendingApiItem === void 0 ? void 0 : pendingApiItem.service.id);
                            if (!opParsed.isSucc) {
                                (_d = this.logger) === null || _d === void 0 ? void 0 : _d.error('ParseServerOutputError: ' + opParsed.errMsg);
                                if (data instanceof Uint8Array) {
                                    (_e = this.logger) === null || _e === void 0 ? void 0 : _e.error('Please check the version of serviceProto between server and client');
                                }
                                if (pendingApiItem) {
                                    (_f = pendingApiItem.onReturn) === null || _f === void 0 ? void 0 : _f.call(pendingApiItem, {
                                        isSucc: false,
                                        err: new TsrpcError('Parse server output error', { type: exports.TsrpcErrorType.ServerError })
                                    });
                                }
                                return [2 /*return*/];
                            }
                            parsed = opParsed.result;
                            if (!(parsed.type === 'api')) return [3 /*break*/, 6];
                            sn = sn !== null && sn !== void 0 ? sn : parsed.sn;
                            // call ApiReturn listeners
                            (_h = (_g = this._pendingApis.find(function (v) { return v.sn === sn; })) === null || _g === void 0 ? void 0 : _g.onReturn) === null || _h === void 0 ? void 0 : _h.call(_g, parsed.ret);
                            return [3 /*break*/, 9];
                        case 6:
                            if (!(parsed.type === 'msg')) return [3 /*break*/, 9];
                            this.options.logMsg && ((_j = this.logger) === null || _j === void 0 ? void 0 : _j.log("[RecvMsg] ".concat(parsed.service.name), parsed.msg));
                            return [4 /*yield*/, this.flows.preRecvMsgFlow.exec({ msgName: parsed.service.name, msg: parsed.msg }, this.logger)];
                        case 7:
                            pre_2 = _k.sent();
                            if (!pre_2) {
                                return [2 /*return*/];
                            }
                            this._msgHandlers.forEachHandler(pre_2.msgName, this.logger, pre_2.msg, pre_2.msgName);
                            // Post Flow
                            return [4 /*yield*/, this.flows.postRecvMsgFlow.exec(pre_2, this.logger)];
                        case 8:
                            // Post Flow
                            _k.sent();
                            _k.label = 9;
                        case 9: return [2 /*return*/];
                    }
                });
            });
        };
        /**
         * @param sn
         * @param timeout
         * @returns `undefined` 代表 canceled
         */
        BaseClient.prototype._waitApiReturn = function (pendingItem, timeout) {
            return __awaiter(this, void 0, void 0, function () {
                var _this = this;
                return __generator(this, function (_a) {
                    return [2 /*return*/, new Promise(function (rs) {
                            // Timeout
                            var timer;
                            if (timeout) {
                                timer = setTimeout(function () {
                                    timer = undefined;
                                    _this._pendingApis.removeOne(function (v) { return v.sn === pendingItem.sn; });
                                    rs({
                                        isSucc: false,
                                        err: new TsrpcError('Request Timeout', {
                                            type: exports.TsrpcErrorType.NetworkError,
                                            code: 'TIMEOUT'
                                        })
                                    });
                                }, timeout);
                            }
                            // Listener (trigger by `this._onRecvBuf`)
                            pendingItem.onReturn = function (ret) {
                                if (timer) {
                                    clearTimeout(timer);
                                    timer = undefined;
                                }
                                _this._pendingApis.removeOne(function (v) { return v.sn === pendingItem.sn; });
                                rs(ret);
                            };
                        })];
                });
            });
        };
        return BaseClient;
    }());
    var defaultBaseClientOptions = {
        logLevel: 'debug',
        logApi: true,
        logMsg: true,
        json: false,
        timeout: 15000,
        debugBuf: false
    };

    /**
     * Base HTTP Client
     */
    var BaseHttpClient = /** @class */ (function (_super) {
        __extends(BaseHttpClient, _super);
        function BaseHttpClient(proto, http, options) {
            var _this = this;
            var _a;
            _this = _super.call(this, proto, __assign(__assign({}, defaultBaseHttpClientOptions), options)) || this;
            _this.type = 'SHORT';
            _this._http = http;
            _this._jsonServer = _this.options.server + (_this.options.server.endsWith('/') ? '' : '/');
            (_a = _this.logger) === null || _a === void 0 ? void 0 : _a.log('TSRPC HTTP Client :', _this.options.server);
            return _this;
        }
        BaseHttpClient.prototype._sendData = function (data, options, serviceId, pendingApiItem) {
            return __awaiter(this, void 0, void 0, function () {
                var promise;
                var _this = this;
                return __generator(this, function (_a) {
                    promise = (function () { return __awaiter(_this, void 0, void 0, function () {
                        var service, urlSearch, url, _a, fetchPromise, abort, fetchRes;
                        return __generator(this, function (_b) {
                            switch (_b.label) {
                                case 0:
                                    service = this.serviceMap.id2Service[serviceId];
                                    urlSearch = service.type === 'msg' ? '?type=msg' : '';
                                    url = typeof data === 'string' ? (this._jsonServer + service.name + urlSearch) : this.options.server;
                                    _a = this._http.fetch({
                                        url: url,
                                        data: data,
                                        method: 'POST',
                                        timeout: options.timeout || this.options.timeout,
                                        headers: { 'Content-Type': typeof data === 'string' ? 'application/json' : 'application/octet-stream' },
                                        transportOptions: options,
                                        responseType: typeof data === 'string' ? 'text' : 'arraybuffer',
                                    }), fetchPromise = _a.promise, abort = _a.abort;
                                    if (pendingApiItem) {
                                        pendingApiItem.onAbort = function () {
                                            abort();
                                        };
                                    }
                                    // Aborted
                                    if (pendingApiItem === null || pendingApiItem === void 0 ? void 0 : pendingApiItem.isAborted) {
                                        return [2 /*return*/, new Promise(function (rs) { })];
                                    }
                                    return [4 /*yield*/, fetchPromise];
                                case 1:
                                    fetchRes = _b.sent();
                                    if (!fetchRes.isSucc) {
                                        return [2 /*return*/, { err: fetchRes.err }];
                                    }
                                    return [2 /*return*/, { res: fetchRes.res }];
                            }
                        });
                    }); })();
                    promise.then(function (v) {
                        // Msg 不需要 onRecvData
                        if (pendingApiItem && v.res) {
                            _this._onRecvData(v.res, pendingApiItem);
                        }
                    });
                    // Finally
                    promise.catch(function (e) { }).then(function () {
                        if (pendingApiItem) {
                            pendingApiItem.onAbort = undefined;
                        }
                    });
                    return [2 /*return*/, promise];
                });
            });
        };
        return BaseHttpClient;
    }(BaseClient));
    var defaultBaseHttpClientOptions = __assign(__assign({}, defaultBaseClientOptions), { server: 'http://localhost:3000', 
        // logger: new TerminalColorLogger(),
        jsonPrune: true });

    /**
     * WebSocket Client for TSRPC.
     * It uses native `WebSocket` of browser.
     * @typeParam ServiceType - `ServiceType` from generated `proto.ts`
     */
    var BaseWsClient = /** @class */ (function (_super) {
        __extends(BaseWsClient, _super);
        function BaseWsClient(proto, wsp, options) {
            var _this = this;
            var _a;
            _this = _super.call(this, proto, __assign(__assign({}, defaultBaseWsClientOptions), options)) || this;
            _this.type = 'LONG';
            _this._onWsOpen = function () {
                var _a;
                if (!_this._connecting) {
                    return;
                }
                _this._status = WsClientStatus.Opened;
                _this._connecting.rs({ isSucc: true });
                _this._connecting = undefined;
                (_a = _this.logger) === null || _a === void 0 ? void 0 : _a.log('WebSocket connection to server successful');
                _this.flows.postConnectFlow.exec({}, _this.logger);
                // First heartbeat
                if (_this.options.heartbeat) {
                    _this._heartbeat();
                }
            };
            _this._onWsClose = function (code, reason) {
                var _a, _b, _c;
                // 防止重复执行
                if (_this._status === WsClientStatus.Closed) {
                    return;
                }
                var isManual = !!_this._rsDisconnecting;
                var isConnectedBefore = _this.isConnected || isManual;
                _this._status = WsClientStatus.Closed;
                // 连接中，返回连接失败
                if (_this._connecting) {
                    _this._connecting.rs({
                        isSucc: false,
                        errMsg: "Failed to connect to WebSocket server: ".concat(_this.options.server)
                    });
                    _this._connecting = undefined;
                    (_a = _this.logger) === null || _a === void 0 ? void 0 : _a.error("Failed to connect to WebSocket server: ".concat(_this.options.server));
                }
                // Clear heartbeat
                if (_this._pendingHeartbeat) {
                    clearTimeout(_this._pendingHeartbeat.timeoutTimer);
                    _this._pendingHeartbeat = undefined;
                }
                if (_this._nextHeartbeatTimer) {
                    clearTimeout(_this._nextHeartbeatTimer);
                }
                // disconnect中，返回成功
                if (_this._rsDisconnecting) {
                    _this._rsDisconnecting();
                    _this._rsDisconnecting = undefined;
                    (_b = _this.logger) === null || _b === void 0 ? void 0 : _b.log('Disconnected succ', "code=".concat(code, " reason=").concat(reason));
                }
                // 非 disconnect 中，从连接中意外断开
                else if (isConnectedBefore) {
                    (_c = _this.logger) === null || _c === void 0 ? void 0 : _c.log("Lost connection to ".concat(_this.options.server), "code=".concat(code, " reason=").concat(reason));
                }
                // postDisconnectFlow，仅从连接状态断开时触发
                if (isConnectedBefore) {
                    _this.flows.postDisconnectFlow.exec({
                        reason: reason,
                        isManual: isManual
                    }, _this.logger);
                }
                // 对所有请求中的 API 报错
                _this._pendingApis.slice().forEach(function (v) {
                    var _a;
                    (_a = v.onReturn) === null || _a === void 0 ? void 0 : _a.call(v, {
                        isSucc: false,
                        err: new TsrpcError(reason || 'Lost connection to server', { type: exports.TsrpcErrorType.NetworkError, code: 'LOST_CONN' })
                    });
                });
            };
            _this._onWsError = function (e) {
                var _a, _b;
                (_a = _this.logger) === null || _a === void 0 ? void 0 : _a.error('[WebSocket Error]', e);
                // 连接中，返回连接失败
                if (_this._connecting) {
                    _this._connecting.rs({
                        isSucc: false,
                        errMsg: "Failed to connect to WebSocket server: ".concat(_this.options.server)
                    });
                    _this._connecting = undefined;
                    (_b = _this.logger) === null || _b === void 0 ? void 0 : _b.error("Failed to connect to WebSocket server: ".concat(_this.options.server));
                }
            };
            _this._onWsMessage = function (data) {
                if (_this._status !== WsClientStatus.Opened) {
                    return;
                }
                // 心跳包回包
                if (data instanceof Uint8Array && data.length === TransportDataUtil.HeartbeatPacket.length && data.every(function (v, i) { return v === TransportDataUtil.HeartbeatPacket[i]; })) {
                    _this._onHeartbeatAnswer(data);
                    return;
                }
                _this._onRecvData(data);
            };
            // #region Heartbeat
            /**
             * Last latency time (ms) of heartbeat test
             */
            _this.lastHeartbeatLatency = 0;
            // #endregion
            _this._status = WsClientStatus.Closed;
            _this._wsp = wsp;
            wsp.options = {
                onOpen: _this._onWsOpen,
                onClose: _this._onWsClose,
                onError: _this._onWsError,
                onMessage: _this._onWsMessage,
                logger: _this.logger
            };
            (_a = _this.logger) === null || _a === void 0 ? void 0 : _a.log('TSRPC WebSocket Client :', _this.options.server);
            return _this;
        }
        BaseWsClient.prototype._sendData = function (data) {
            return __awaiter(this, void 0, void 0, function () {
                var _this = this;
                return __generator(this, function (_a) {
                    return [2 /*return*/, new Promise(function (rs) { return __awaiter(_this, void 0, void 0, function () {
                            return __generator(this, function (_a) {
                                if (!this.isConnected) {
                                    rs({
                                        err: new TsrpcError('WebSocket is not connected', {
                                            code: 'WS_NOT_OPEN',
                                            type: TsrpcError.Type.ClientError
                                        })
                                    });
                                    return [2 /*return*/];
                                }
                                // Do Send
                                rs(this._wsp.send(data));
                                return [2 /*return*/];
                            });
                        }); })];
                });
            });
        };
        /**
         * Send a heartbeat packet
         */
        BaseWsClient.prototype._heartbeat = function () {
            var _this = this;
            var _a;
            if (this._pendingHeartbeat || this._status !== WsClientStatus.Opened || !this.options.heartbeat) {
                return;
            }
            this._pendingHeartbeat = {
                startTime: Date.now(),
                timeoutTimer: setTimeout(function () {
                    var _a;
                    _this._pendingHeartbeat = undefined;
                    // heartbeat timeout, disconnect if still connected
                    (_a = _this.logger) === null || _a === void 0 ? void 0 : _a.error('[Heartbeat] Heartbeat timeout, the connection disconnected automatically.');
                    _this._wsClose(3000, 'Heartbeat timeout');
                    _this._wsp.options.onClose(3000, 'Heartbeat timeout');
                }, this.options.heartbeat.timeout)
            };
            this.options.debugBuf && ((_a = this.logger) === null || _a === void 0 ? void 0 : _a.log('[Heartbeat] Send ping', TransportDataUtil.HeartbeatPacket));
            this._sendData(TransportDataUtil.HeartbeatPacket);
        };
        BaseWsClient.prototype._onHeartbeatAnswer = function (data) {
            var _this = this;
            var _a;
            if (!this._pendingHeartbeat || this._status !== WsClientStatus.Opened || !this.options.heartbeat) {
                return;
            }
            // heartbeat succ
            this.lastHeartbeatLatency = Date.now() - this._pendingHeartbeat.startTime;
            this.options.debugBuf && ((_a = this.logger) === null || _a === void 0 ? void 0 : _a.log("[Heartbeat] Recv pong, latency=".concat(this.lastHeartbeatLatency, "ms"), data));
            clearTimeout(this._pendingHeartbeat.timeoutTimer);
            this._pendingHeartbeat = undefined;
            // next heartbeat timer
            this._nextHeartbeatTimer = setTimeout(function () {
                _this._heartbeat();
            }, this.options.heartbeat.interval);
        };
        Object.defineProperty(BaseWsClient.prototype, "status", {
            get: function () {
                return this._status;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(BaseWsClient.prototype, "isConnected", {
            get: function () {
                return this._status === WsClientStatus.Opened;
            },
            enumerable: false,
            configurable: true
        });
        /**
         * Start connecting, you must connect first before `callApi()` and `sendMsg()`.
         * @throws never
         */
        BaseWsClient.prototype.connect = function () {
            var _a, _b;
            return __awaiter(this, void 0, void 0, function () {
                var pre, promiseConnect;
                var _this = this;
                return __generator(this, function (_c) {
                    switch (_c.label) {
                        case 0:
                            // 已连接成功
                            if (this.isConnected) {
                                return [2 /*return*/, { isSucc: true }];
                            }
                            // 已连接中
                            if (this._connecting) {
                                return [2 /*return*/, this._connecting.promise];
                            }
                            return [4 /*yield*/, this.flows.preConnectFlow.exec({}, this.logger)];
                        case 1:
                            pre = _c.sent();
                            // Pre return
                            if (pre === null || pre === void 0 ? void 0 : pre.return) {
                                return [2 /*return*/, pre.return];
                            }
                            // Canceled
                            if (!pre) {
                                return [2 /*return*/, new Promise(function (rs) { })];
                            }
                            try {
                                this._wsp.connect(this.options.server, [this.options.json ? 'text' : 'buffer']);
                            }
                            catch (e) {
                                (_a = this.logger) === null || _a === void 0 ? void 0 : _a.error(e);
                                return [2 /*return*/, { isSucc: false, errMsg: e.message }];
                            }
                            this._status = WsClientStatus.Opening;
                            (_b = this.logger) === null || _b === void 0 ? void 0 : _b.log("Start connecting ".concat(this.options.server, "..."));
                            this._connecting = {};
                            promiseConnect = new Promise(function (rs) {
                                _this._connecting.rs = rs;
                            });
                            this._connecting.promise = promiseConnect;
                            return [2 /*return*/, promiseConnect];
                    }
                });
            });
        };
        /**
         * Disconnect immediately
         * @throws never
         */
        BaseWsClient.prototype.disconnect = function (code, reason) {
            var _a;
            return __awaiter(this, void 0, void 0, function () {
                var isClosed;
                var _this = this;
                return __generator(this, function (_b) {
                    if (this._status === WsClientStatus.Closed) {
                        return [2 /*return*/];
                    }
                    this._status = WsClientStatus.Closing;
                    (_a = this.logger) === null || _a === void 0 ? void 0 : _a.log('Start disconnecting...');
                    isClosed = false;
                    return [2 /*return*/, Promise.race([
                            // 正常等待 onClose 关闭
                            new Promise(function (rs) {
                                _this._rsDisconnecting = function () {
                                    if (isClosed) {
                                        return;
                                    }
                                    isClosed = true;
                                    rs();
                                };
                                _this._wsClose(code !== null && code !== void 0 ? code : 1000, reason !== null && reason !== void 0 ? reason : '');
                            }),
                            // 超时保护，1 秒未收到关闭请求的，直接 onClose 掉
                            new Promise(function (rs) {
                                setTimeout(function () {
                                    if (isClosed) {
                                        return;
                                    }
                                    isClosed = true;
                                    _this._onWsClose(1005, 'Connection closed, but not received ws.onClose event.');
                                }, 1000);
                            })
                        ])];
                });
            });
        };
        BaseWsClient.prototype._wsClose = function (code, reason) {
            var _a;
            try {
                this._wsp.close(code !== null && code !== void 0 ? code : 1000, reason !== null && reason !== void 0 ? reason : '');
            }
            catch (e) {
                (_a = this.logger) === null || _a === void 0 ? void 0 : _a.error('[WsCloseError]', e);
            }
        };
        return BaseWsClient;
    }(BaseClient));
    var defaultBaseWsClientOptions = __assign(__assign({}, defaultBaseClientOptions), { server: 'ws://localhost:3000' });
    var WsClientStatus;
    (function (WsClientStatus) {
        WsClientStatus["Opening"] = "OPENING";
        WsClientStatus["Opened"] = "OPENED";
        WsClientStatus["Closing"] = "CLOSING";
        WsClientStatus["Closed"] = "CLOSED";
    })(WsClientStatus || (WsClientStatus = {}));

    /**
     * @internal
     */
    var HttpProxy = /** @class */ (function () {
        function HttpProxy() {
        }
        HttpProxy.prototype.fetch = function (options) {
            var _this = this;
            var _a;
            var rs;
            var promise = new Promise(function (_rs) {
                rs = _rs;
            });
            var xhr = new XMLHttpRequest();
            if (typeof navigator !== 'undefined' && ((_a = navigator === null || navigator === void 0 ? void 0 : navigator.userAgent) === null || _a === void 0 ? void 0 : _a.indexOf('MSIE 8.0;')) > -1) {
                //IE8 不支持onload onabort onerror事件
                xhr.onreadystatechange = function () { return __awaiter(_this, void 0, void 0, function () {
                    return __generator(this, function (_a) {
                        if (xhr.readyState == 4) {
                            //Network Error
                            if (xhr.status == 0 || (xhr.response == null && xhr.responseText == null)) {
                                rs({
                                    isSucc: false,
                                    err: new TsrpcError('Network Error', {
                                        type: TsrpcError.Type.NetworkError,
                                        httpCode: xhr.status
                                    })
                                });
                                return [2 /*return*/];
                            }
                            //IE9 wrongURL 会返回12029
                            if (xhr.status == 12029) {
                                rs({
                                    isSucc: false,
                                    err: new TsrpcError({
                                        message: 'Network Error',
                                        type: TsrpcError.Type.NetworkError,
                                        httpCode: xhr.status
                                    })
                                });
                                return [2 /*return*/];
                            }
                            // Res
                            rs({
                                isSucc: true,
                                res: options.responseType === 'text' ? xhr.responseText : new Uint8Array(xhr.response)
                            });
                        }
                        return [2 /*return*/];
                    });
                }); };
            }
            else {
                xhr.onerror = function () {
                    rs({
                        isSucc: false,
                        err: new TsrpcError({
                            message: 'Network Error',
                            type: TsrpcError.Type.NetworkError,
                            httpCode: xhr.status
                        })
                    });
                };
                // 有的平台 超时不触发onerror
                xhr.ontimeout = function () {
                    rs({
                        isSucc: false,
                        err: new TsrpcError({
                            message: 'Request Timeout',
                            type: TsrpcError.Type.NetworkError,
                            code: 'TIMEOUT'
                        })
                    });
                };
                // Res
                xhr.onload = function () { return __awaiter(_this, void 0, void 0, function () {
                    return __generator(this, function (_a) {
                        if (xhr.status === 200 || xhr.status === 500) {
                            rs({
                                isSucc: true,
                                res: xhr.response && (options.responseType === 'text' ? xhr.responseText : new Uint8Array(xhr.response))
                            });
                        }
                        else {
                            rs({
                                isSucc: false,
                                err: new TsrpcError({
                                    message: 'HTTP Error ' + xhr.status,
                                    type: TsrpcError.Type.ServerError,
                                    httpCode: xhr.status
                                })
                            });
                        }
                        return [2 /*return*/];
                    });
                }); };
                var transportOptions_1 = options.transportOptions;
                if (!!transportOptions_1.onProgress) {
                    xhr.upload.onprogress = function (e) {
                        var _a;
                        (_a = transportOptions_1.onProgress) === null || _a === void 0 ? void 0 : _a.call(transportOptions_1, e.loaded / e.total);
                    };
                }
            }
            xhr.open(options.method, options.url, true);
            if (options.headers) {
                for (var key in options.headers) {
                    xhr.setRequestHeader(key, options.headers[key]);
                }
            }
            xhr.responseType = options.responseType;
            var timeout = options.timeout;
            if (timeout) {
                xhr.timeout = timeout;
            }
            xhr.send(options.data);
            var abort = xhr.abort.bind(xhr);
            return {
                promise: promise,
                abort: abort
            };
        };
        return HttpProxy;
    }());

    /**
     * HTTP Client for TSRPC.
     * It uses XMLHttpRequest to send requests.
     * @typeParam ServiceType - `ServiceType` from generated `proto.ts`
     */
    var HttpClient = /** @class */ (function (_super) {
        __extends(HttpClient, _super);
        function HttpClient(proto, options) {
            var httpProxy = new HttpProxy;
            return _super.call(this, proto, httpProxy, __assign(__assign({}, defaultHttpClientOptions), options)) || this;
        }
        HttpClient.prototype.callApi = function (apiName, req, options) {
            if (options === void 0) { options = {}; }
            return _super.prototype.callApi.call(this, apiName, req, options);
        };
        HttpClient.prototype.sendMsg = function (msgName, msg, options) {
            if (options === void 0) { options = {}; }
            return _super.prototype.sendMsg.call(this, msgName, msg, options);
        };
        return HttpClient;
    }(BaseHttpClient));
    var defaultHttpClientOptions = __assign(__assign({}, defaultBaseHttpClientOptions), { customObjectIdClass: String });

    /**
     * @internal
     */
    var WebSocketProxy = /** @class */ (function () {
        function WebSocketProxy(caUrl) {
            this.caUrl = caUrl;
        }
        WebSocketProxy.prototype.connect = function (server, protocols) {
            var _this = this;
            if (this.caUrl) {
                // @ts-ignore
                this._ws = new WebSocket(server, protocols, this.caUrl);
            }
            else {
                this._ws = new WebSocket(server, protocols);
            }
            this._ws.binaryType = 'arraybuffer';
            this._ws.onopen = this.options.onOpen;
            this._ws.onerror = this.options.onError;
            this._ws.onclose = function (e) {
                _this.options.onClose(e.code, e.reason);
                _this._ws = undefined;
            };
            this._ws.onmessage = function (e) {
                var _a;
                if (e.data instanceof ArrayBuffer) {
                    _this.options.onMessage(new Uint8Array(e.data));
                }
                else if (typeof e.data === 'string') {
                    _this.options.onMessage(e.data);
                }
                else {
                    (_a = _this.options.logger) === null || _a === void 0 ? void 0 : _a.warn('[Unresolved Recv]', e.data);
                }
            };
        };
        WebSocketProxy.prototype.close = function (code, reason) {
            var _a;
            (_a = this._ws) === null || _a === void 0 ? void 0 : _a.close(code, reason);
            this._ws = undefined;
        };
        WebSocketProxy.prototype.send = function (data) {
            return __awaiter(this, void 0, void 0, function () {
                var sendData, buf;
                return __generator(this, function (_a) {
                    try {
                        sendData = void 0;
                        if (typeof data === 'string') {
                            sendData = data;
                        }
                        else {
                            buf = data;
                            if (buf.byteOffset === 0 && buf.byteLength === buf.buffer.byteLength) {
                                sendData = buf.buffer;
                            }
                            else {
                                sendData = buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
                            }
                        }
                        this._ws.send(sendData);
                        return [2 /*return*/, {}];
                    }
                    catch (err) {
                        return [2 /*return*/, {
                                err: new TsrpcError('Network Error', {
                                    code: 'SEND_BUF_ERR',
                                    type: TsrpcError.Type.NetworkError,
                                    innerErr: err
                                })
                            }];
                    }
                    return [2 /*return*/];
                });
            });
        };
        return WebSocketProxy;
    }());

    /**
     * Client for TSRPC WebSocket Server.
     * @typeParam ServiceType - `ServiceType` from generated `proto.ts`
     */
    var WsClient = /** @class */ (function (_super) {
        __extends(WsClient, _super);
        function WsClient(proto, options) {
            var wsp = new WebSocketProxy(options === null || options === void 0 ? void 0 : options.caUrl);
            return _super.call(this, proto, wsp, __assign(__assign({}, defaultWsClientOptions), options)) || this;
        }
        return WsClient;
    }(BaseWsClient));
    var defaultWsClientOptions = __assign(__assign({}, defaultBaseWsClientOptions), { customObjectIdClass: String });

    exports.HttpClient = HttpClient;
    exports.TransportDataProto = TransportDataProto;
    exports.TsrpcError = TsrpcError;
    exports.WsClient = WsClient;
    exports.setLogLevel = setLogLevel;

    Object.defineProperty(exports, '__esModule', { value: true });

}));
